简体   繁体   English

将JPanel中的当前图像替换为另一幅图像

[英]Replace current image in JPanel with another one

I´m writing a program where images are displayed on a JPanel, but I´m having trouble replacing the existing image when I open a new one. 我正在写一个程序,其中图像显示在JPanel上,但是打开新图像时,我很难替换现有图像。 Is there a easy way to remove the old image from the ImageIcon and replace with the new one? 是否有一种简单的方法可以从ImageIcon中删除旧图像并替换为新图像? I thought that something like mp.remove(pic); 我以为是mp.remove(pic); would work here, but it says that it´s not supported for ImageIcon? 可以在这里工作,但是它说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);
    }

}

Why are you using ImageIcon at all? 为什么要使用ImageIcon? It appears you want to draw an Image in a JPanel, not sure why you are using ImageIcon. 似乎您想在JPanel中绘制图像,不确定为什么要使用ImageIcon。 Use ImageIO.read() to read the file chosen by the file chooser as an BufferedImage. 使用ImageIO.read()读取文件选择器选择的文件作为BufferedImage。 Set the image to a member variable, then in paintComponent() instead of pic.getImage(), use your member variable. 将图像设置为成员变量,然后在paintComponent()而不是pic.getImage()中使用您的成员变量。 After a file is chosen and you set your member variable to the new file call repaint(). 选择文件并将您的成员变量设置为新文件后,调用repaint()。

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

Also, setting preferredSize, min size, and max size may or may not do anything. 另外,设置preferredSize,min size和max size可能会也可能不会做任何事情。 It all depends on what layout manager the container you put this JPanel in is using. 这完全取决于您将此JPanel放入的容器所使用的布局管理器。

Not sure if this will work for what you want to do but give it a try. 不知道这是否能满足您的需求,请尝试一下。

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

or just pass in an Image there. 或只是在其中传递图片。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM