Java 单击按钮时如何更改JButton上的图像?

Java 单击按钮时如何更改JButton上的图像?,java,swing,jbutton,Java,Swing,Jbutton,我已经实现了这段代码,但是eclipse告诉我“lunarButton无法解析”,它是否无法在我的init()方法中看到lunarButton变量?这里缺少什么?您的lunarButton可能在本地声明,可能在init方法中声明 一种解决方案是:将其声明为类中的实例字段,而不是init方法中的实例字段 解决方案二:甚至不用担心变量。从ActionEvent参数的getSource()方法获取JButton对象。将返回的对象强制转换为JButton,并对其调用您想要的任何方法 例如: public


我已经实现了这段代码,但是eclipse告诉我“lunarButton无法解析”,它是否无法在我的init()方法中看到lunarButton变量?这里缺少什么?

您的lunarButton可能在本地声明,可能在init方法中声明

一种解决方案是:将其声明为类中的实例字段,而不是init方法中的实例字段

解决方案二:甚至不用担心变量。从ActionEvent参数的
getSource()
方法获取JButton对象。将返回的对象强制转换为JButton,并对其调用您想要的任何方法

例如:

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);
        }

顺便说一句:您真的不想每次按下按钮时都从磁盘重新加载图像。相反,在中读取一次图像,可能是在构造函数中,将它们填充到ImageIcon字段中,并在需要时使用该字段。

您是否将
lunarButton
作为类的实例变量?正如您所说,我将其作为一个实例字段,并且它工作正常(谢谢,我会记住您的其他方法=)。我会在它允许的时候检查
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);
        }
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);
    }