有人发贴问,一个 JPanel 里的图片太大了,超出了 JPanel 的大小范围,“我想拖动鼠标按住JPanel,拖动JPanel,把那些显示不了的线段“拖回来”。”
这是 JViewport 的典型应用场景,很多人会用 JScrollPane,但是对 JViewport 可能不熟悉,其实 JScrollPane 是整合了几个 JViewport,JScrollBar,以及特别设计的布局的一个控件,其中的 JViewport 单独拿出来也很好用,下面就是示例代码。
为了显示图片,先做一个 panel,如下
/*
* Copyright 2013 (raistlic@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import javax.swing.JPanel;
/**
*
* @author raistlic
*/
public class JImagePanel extends JPanel {
private static final Color GRID_1 = Color.GRAY.brighter();
private static final Color GRID_2 = GRID_1.brighter();
private static final int GRID_SIZE = 10;
private Image image;
public void setImage(Image image) {
// although not checked, this method should be called with-in EDT.
this.image = image;
revalidate();
repaint();
}
@Override
public Dimension getPreferredSize() {
if( image == null )
return getMinimumSize();
else {
Insets i = getInsets();
return new Dimension(
i.left + i.right + image.getWidth(this),
i.top + i.bottom + image.getHeight(this));
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWi