该程序只需在面板上添加按钮即可,单击该按钮后,屏幕应变为指定按钮的颜色。基本上,我需要更改蓝色按钮以执行完全相同的操作,但是使用匿名内部类,我感觉自己处在正确的轨道上,但是却收到了很多错误。我看过许多匿名内部类的示例,并且我相信我在正确地编写代码,但是与编译器无法找到符号有关,这有很多错误,而我并没有完全理解。任何帮助将不胜感激,因为我已经为此工作了2天,我希望在本周内解决它。这是我的代码:(很多东西都被注释掉了,所以我一次可以专注于一个按钮)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


这是我试图添加匿名内部类的地方:

class Blue
{
  public void start()
  {
     ActionListener listener = new Blue();
  }
  public class Blue implements ActionListener
  {
    public void actionPerformed(ActionEvent event)
    {
            Object source = evt.getSource();
            Color color = getBackground();
            color = Color.blue;
            setBackground(color);
            repaint();
    }
  }
}

class ButtonPanel extends JPanel //implements ActionListener
{
   private JButton yellowButton;
   private JButton blueButton;
   private JButton redButton;
   private JButton greenButton;

public ButtonPanel()
{
    //yellowButton = new JButton("Yellow");
    //redButton = new JButton("Red");
    blueButton = new JButton("Blue");
    //greenButton = new JButton("Green");

    //add(yellowButton);
    //add(redButton);
    add(blueButton);
    //add(greenButton);

    //yellowButton.addActionListener(this);

    blueButton.addActionListener(listener);
    //greenButton.addActionListener(this);

    /*class Red
    {
        public void red()
        {
            ActionListener listener = new ActionListener();
            redButton.addActionListener(listener);
        }
        class turnRed implements ActionListener
        {
            public void actionPerformed(ActionEvent event)
            {
                setBackground(Color.red);
                repaint();
            }
        }
    }*/
}


/*public void actionPerformed(ActionEvent evt)
{
    Object source = evt.getSource();
    Color color = getBackground();
    if (source == yellowButton) color = Color.yellow;
    else if (source == blueButton) color = Color.blue;
    else if (source == redButton) color = Color.red;
    else if (source == greenButton) color = Color.green;
    setBackground(color);
    repaint();
}
}


class ButtonFrame extends JFrame
{
  public ButtonFrame()
  {
    setTitle("ButtonTest");
    setSize(300, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.add(new ButtonPanel());
  }
}

public class ButtonTest
{
   public static void main(String[] args)
   {
      JFrame frame = new ButtonFrame();
      frame.setVisible(true);
   }
}

最佳答案

代替使用listener变量,而创建(新创建的)匿名内部类的实例。这是这样做的:

blueButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        Object source = evt.getSource();
        Color color = getBackground();
        color = Color.blue;
        setBackground(color);
        repaint();
    }
});

09-11 10:42