JScrollPane为空,直到您滚动。

时间:2015-09-27 22:25:27

标签: java swing scroll pane

我在框架中实现了如此实现的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适应新图像而无需用户滚动?

由于

1 个答案:

答案 0 :(得分:3)

setImage(...)方法也应该调用:

img = bi; 
revalidate(); // to invoke the layout manager
repaint();  // paint itself