java单击按钮时如何更改JButton上的图像?
JButton lunarButton = new JButton(new ImageIcon("assets/Buttons/moon.png"));
lunarButton.setActionCommand("switch");
c.gridwidth=1;
c.gridy = 0;
searchArea.add(lunarButton, c);
public void actionPerformed(ActionEvent ev)
{
int count = 1;
String action = ev.getActionCommand();
if("switch".equals(action))
{
ImageIcon sun = new ImageIcon("assets/sun.png");
ImageIcon moon = new ImageIcon("assets/moon.png");
changeLunar();
count++;
if (count % 2 == 0)
{
lunarButton.setIcon(sun);
}
else
{
lunarButton.setIcon(moon);
}
我已经实现了这段代码,但eclipse告诉我“lunarButton无法解析”,它是否无法在我的init()方法中看到lunarButton变量?我错过了什么
# 1 楼答案
您的lunarButton可能会在本地声明,可能是在init方法中
一种解决方案是:在类中将其声明为实例字段,而不是在init方法中
解决方案二:甚至不用担心变量。从ActionEvent参数的
getSource()
方法获取JButton对象。将返回的对象强制转换为JButton,并对其调用任何方法例如:
顺便说一句:你真的不想每次按下按钮都从磁盘重新加载图像。相反,在中读取一次图像,或者在构造函数中,将它们填充到ImageIcon字段中,并在需要时使用该字段