我创建了一个名为 ImagePanel 的自定义 JPanel 类。我像这样重写 PaintComponent 方法...
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0,0, null);
}
自定义面板的目的是简单地绘制图像。
在我的 JFrame 中,我创建了一个添加到 JFrame 的 ScollPane。当我创建 ScrollPane 时,我传入了 imagePanel 的实例,如下所示...
ip = new ImagePanel();
JScrollPane jsp = new JScrollPane(ip);
this.add(jsp);
现在我想要的是一种使用滚动条滚动图像的易于使用的方式。现在图像非常大并且不出现滚动条。我使用该策略使它们可见,但滚动条的句柄不存在。
有人知道一个简单的方法吗?
最佳答案
尝试使用JPanel#setPreferredSize()如果需要,这将强制 JScrollPane
显示滚动条。
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0,0, null);
// set the size of the panel based on image size
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
}
<小时/>
编辑
在重写的 paintComponent()
中设置 setPreferredSize()
并不是一个好方法。
您可以按照 @mKorbel
的建议,使用 JLabel
以更简单的方式完成此操作。欲了解更多信息,请查看下面的评论。
BufferedImage image = ...
JLabel label = new JLabel(new ImageIcon(image)); // set the icon
JScrollPane jsp = new JScrollPane(label);
屏幕截图:
关于java - 使用 JScrollPane 和 JPanel (自定义)滚动某个矩形的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23663308/