[英]How do I change the image on a JButton when clicked?
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);
}
I have this code implemented, but eclipse tells me "lunarButton cannot be resolved", is it not able to see the lunarButton variable in my init() method? 我已经实现了这段代码,但是eclipse告诉我“ lunarButton无法解析”,它无法在init()方法中看到lunarButton变量吗? what am I missing here?
我在这里想念什么?
Your lunarButton may be declared locally, perhaps in the init method. 您的lunarButton可能在本地声明,也许在init方法中。
One solution: declare it as an instance field in the class, not in the init method. 一种解决方案:在类中而不是在init方法中将其声明为实例字段。
Solution two: don't even worry about the variable. 解决方案二:甚至不用担心变量。 Get the JButton object from the ActionEvent parameter's
getSource()
method. 从ActionEvent参数的
getSource()
方法获取JButton 对象 。 Cast the object returned to JButton, and call whatever methods you'd like on it. 将返回的对象强制转换为JButton,然后调用您想要的任何方法。
For example: 例如:
if("switch".equals(action))
{
// ImageIcon sun = new ImageIcon("assets/sun.png");
// ImageIcon moon = new ImageIcon("assets/moon.png");
JButton btn = (JButton) ae.getSource();
changeLunar();
count++;
if (count % 2 == 0)
{
btn.setIcon(sun);
}
else
{
btn.setIcon(moon);
}
As an aside: you really don't want to re-load the images from disk each time the button is pushed. 顺便说一句:您确实不希望每次按下按钮时都从磁盘重新加载图像。 Instead read the images in once , perhaps in a constructor, stuff them into an ImageIcon field, and use that field when needed.
而是一次读取图像,也许是在构造函数中读取图像,将其填充到ImageIcon字段中,并在需要时使用该字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.