Domanda

I have a JButton with an image as an Icon, and I want it to change after I have clicked it. 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. If I do it, then I get an error on the constructor and it asks me to remove the final from the JButton variable. 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?

È stato utile?

Soluzione

Create the ImageIcon once and store somewhere e.g. in the class' static field(s). 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.

UPDATE define a method like this

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());
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top