我有一个带有图像作为图标的 JButton,我希望它在单击它后发生变化。但是,由于它迫使我使用 try/catch 来 setIcon,所以我将它用于构造函数,但是,在该按钮的 actionPerformed 方法中,如果我再次在 JButton 变量上使用 setIcon,它会强制我将变量更改为最终的。如果我这样做,那么我会在构造函数上收到错误,并要求我从 JButton 变量中删除final。这就是我的意思:
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"))));
}
});
我怎样才能让它发挥作用?
最佳答案
创建一次ImageIcon
并存储在某个地方,例如在类的静态字段中。然后只需使用将图像分配给按钮的字段即可。
您可以在静态部分初始化图像或创建图像 getter 来检查图像是否==null并从文件创建它们。
更新定义这样的方法
public static ImageIcon getImage1() {
try {
return new ImageIcon(ImageIO.read(new File("imatges/Mapa.png")))
} catch (IOException e2) {
e2.printStackTrace();
}
return null;
}
并使用该方法创建按钮
butoMapa = new JButton(getImage1());
关于java - 使用JButton后如何更改图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23496235/