简体   繁体   English

如何在使用后更改JButton图标?

[英]How to change a JButton Icon after using it?

I have a JButton with an image as an Icon, and I want it to change after I have clicked it. 我有一个带有图像的JButton作为Icon,我希望它在点击之后能够改变。 However, since it forces me to use try/catch to setIcon, I use it for the contructor, but then, in the actionPerformed method of that button, if I use setIcon again on the JButton variable, it forces me to change the variable to final. 但是,因为它迫使我使用try / catch来设置setIcon,我将它用于构造函数,但是,在那个按钮的actionPerformed方法中,如果我再次在JButton变量上使用setIcon,它会强制我将变量更改为最后。 If I do it, then I get an error on the constructor and it asks me to remove the final from the JButton variable. 如果我这样做,那么我在构造函数上得到一个错误,它要求我从JButton变量中删除final。 Here's what I mean: 这就是我的意思:

JButton butoMapa = null;
        try {
            butoMapa = new JButton(new ImageIcon(ImageIO.read(new File("imatges/Mapa.png"))));
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        butoMapa.updateUI();
        butoMapa.setContentAreaFilled(false);
        butoMapa.setBorderPainted(false);
        butoMapa.setFocusPainted(false);
        butoMapa.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent evt) {
                 m = entrarFitxer();
                 butoMapa.setIcon(new ImageIcon(ImageIO.read(new File("imatges/MapaOK.png"))));
             }
        });

How can I make it work? 我怎样才能使它工作?

Create the ImageIcon once and store somewhere eg in the class' static field(s). 创建一次ImageIcon并存储在某个地方,例如在类的静态字段中。 Then just use the fields assigning the images to buttons. 然后只需使用将图像分配给按钮的字段。

You cna initialize the images in static section or create the images getters which check whether the images ==null and creates them from file. 您可以在静态部分初始化图像,或者创建图像获取器,检查图像是否== null并从文件创建它们。

UPDATE define a method like this UPDATE定义这样的方法

public static ImageIcon getImage1() {
  try {
      return new ImageIcon(ImageIO.read(new File("imatges/Mapa.png")))
  } catch (IOException e2) {
      e2.printStackTrace();
  }
  return null;
}

And use the method for the button creation 并使用该方法创建按钮

butoMapa = new JButton(getImage1());

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

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