繁体   English   中英

如何更换新的imageIcon?

[英]How to replace a new imageIcon?

String mycon="image1.png";

public LottoGUI(String one, String two,String three) {
    Container C= getContentPane();
    C.setLayout(new FlowLayout());
    JLabel MyImage = new JLabel(new ImageIcon(mycon));
    JButton labb =    new JButton("OK!");
    labb.addActionListener(this);
    C.add(MyImage);
    C.add(labb) 
}

public void actionPerformed(ActionEvent e) {
    if(e.getSource()==labb){}
}

按下按钮后如何将图片从image1更改为新图像

1)尝试使用setIcon方法。 如果这不起作用,请2)更换
整个JLabel对象,并带有一个新对象(带有新图标)。

JLabel setIcon

如果使用第二种方法,则需要
MyImage转换为类变量。

有点题外话

您不应该从文件系统加载图像。 当您传递路径String ImageIcon ,您最终将告诉它在文件系统中查找图像。 尽管这在IDE的开发期间可能会起作用,但是您会发现在部署时它不会起作用。

相反,您应该通过URL将图像作为嵌入式资源加载。 可以使用Class.getResource()获得URL。 资源将从类路径中按需查找。 这是一个例子

ImageIcon icon = new ImageIcon(MyClass.class.getResource("/resources/image.png"));

image.png在此位于src的资源包中,它将在构建时复制到类路径中

ProjectRoot
          src
              resources
                      image.png

返回主题

至于您的主要问题,如@ peter.petrov所述,您应该使用.setIcon(icon); 并使MyImage成为具有全局范围的类成员,以便可以在其他代码块中对其进行访问。 现在,它仅在构造函数中本地作用域

String mycon="image1.png";
JLabel MyImage;

public LottoGUI(String one, String two,String three) {
    Container C= getContentPane();
    C.setLayout(new FlowLayout());
    MyImage = new JLabel(new ImageIcon(mycon));
    JButton labb =    new JButton("OK!");
    labb.addActionListener(this);
    C.add(MyImage);
    C.add(labb) 
}

public void actionPerformed(ActionEvent e) {
    if(e.getSource()==labb){
        MyImage.setIcon(newIcon);
    }
}

另请注意Java命名约定。 变量应以小写字母开头,即MyImage应该是myImage

在JButton click事件上使用此行

jLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/one.png")));

"/images/one.png"替换为您的课程路径。

谢谢

暂无
暂无

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

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