JScrollPane 空白,直到您滚动。
JScrollPane blank until you scroll.
我在框架中实现了一个 JScrollPane:
public ImagePanel imgPane = new ImagePanel();
JScrollPane scrollPane = new JScrollPane(imgPane);
ImagePanel 是 JPanel 的扩展:
public class ImagePanel extends JPanel {
private BufferedImage img;
public ImagePanel(BufferedImage img) {
this.img = img;
}
public ImagePanel() {
}
@Override
public Dimension getPreferredSize() {
return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(), img.getHeight());
}
protected Point getImageLocation() {
Point p = null;
if (img != null) {
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
p = new Point(x, y);
}
return p;
}
public void setImage(BufferedImage bi) {
img = bi;
}
public Point toImageContext(Point p) {
Point imgLocation = getImageLocation();
Point relative = new Point(p);
relative.x -= imgLocation.x;
relative.y -= imgLocation.y;
return relative;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
Point p = getImageLocation();
g.drawImage(img, p.x, p.y, this);
}
}
我遇到的问题是,当我将图像加载到窗格中时:
frame.imgPane.setImage(img);
除非上一个图像大小相同,否则窗格显示为空白,没有图像,直到您滚动。 imgPane.repaint() 对此没有影响。有没有办法让 JScrollPane 适应新图像而无需用户滚动?
谢谢
setImage(...)
方法还应调用:
img = bi;
revalidate(); // to invoke the layout manager
repaint(); // paint itself
我在框架中实现了一个 JScrollPane:
public ImagePanel imgPane = new ImagePanel();
JScrollPane scrollPane = new JScrollPane(imgPane);
ImagePanel 是 JPanel 的扩展:
public class ImagePanel extends JPanel {
private BufferedImage img;
public ImagePanel(BufferedImage img) {
this.img = img;
}
public ImagePanel() {
}
@Override
public Dimension getPreferredSize() {
return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(), img.getHeight());
}
protected Point getImageLocation() {
Point p = null;
if (img != null) {
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
p = new Point(x, y);
}
return p;
}
public void setImage(BufferedImage bi) {
img = bi;
}
public Point toImageContext(Point p) {
Point imgLocation = getImageLocation();
Point relative = new Point(p);
relative.x -= imgLocation.x;
relative.y -= imgLocation.y;
return relative;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
Point p = getImageLocation();
g.drawImage(img, p.x, p.y, this);
}
}
我遇到的问题是,当我将图像加载到窗格中时:
frame.imgPane.setImage(img);
除非上一个图像大小相同,否则窗格显示为空白,没有图像,直到您滚动。 imgPane.repaint() 对此没有影响。有没有办法让 JScrollPane 适应新图像而无需用户滚动?
谢谢
setImage(...)
方法还应调用:
img = bi;
revalidate(); // to invoke the layout manager
repaint(); // paint itself