用另一个替换JPanel中的当前图像

时间:2017-05-18 14:32:01

标签: java image swing jpanel imageicon

我正在编写一个程序,其中图像显示在JPanel上,但是当我打开一个新图像时,我无法替换现有图像。有没有一种简单的方法可以从ImageIcon中删除旧图像并替换为新图像?我认为像 mp.remove(pic); 这样的东西可以在这里工作,但它说ImageIcon不支持它?

class MapPanel extends JPanel {

public MapPanel(String filename) {
    if(mp == null) {
    pic = new ImageIcon(filename);
    int w = pic.getIconWidth();
    int h = pic.getIconHeight();
    setPreferredSize(new Dimension(w, h));
    setMinimumSize(new Dimension(w, h));
    setMaximumSize(new Dimension(w, h));
    setLayout(null);
}
    else { int confirm = 
JOptionPane.showConfirmDialog(MapProgram.this, "Unsaved changes, " + 
"do you really want to open a new map?",
            "New map", JOptionPane.OK_CANCEL_OPTION);
            if (confirm != JOptionPane.OK_OPTION)
                return;     

    // Remove the current image and display the new one choosen 
    // from the JFileChooser.


    }       
}
protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(pic.getImage(), 0, 0, this);
    }

}

2 个答案:

答案 0 :(得分:0)

你为什么要使用ImageIcon?您似乎想要在JPanel中绘制图像,不确定为什么使用ImageIcon。使用ImageIO.read()将文件选择器选择的文件读取为BufferedImage。将图像设置为成员变量,然后在paintComponent()而不是pic.getImage()中,使用您的成员变量。选择文件并将成员变量设置为新文件后,调用repaint()。

https://docs.oracle.com/javase/8/docs/api/javax/imageio/ImageIO.html#read-java.io.File-

此外,设置preferredSize,min size和max size可能会也可能不会执行任何操作。这一切都取决于你放置这个JPanel的容器使用的布局管理器。

答案 1 :(得分:-1)

不确定这是否适用于您想要做的事情,但请尝试一下。

g.drawImage(new ImageIcon(filename).getImage(), 0, 0, this);

或者只是传入一张图片。

相关问题