找不到 JButton 变量

JButton variable not found

我试图在单击单选按钮时更改背景颜色,但是编译器找不到第二个单选按钮 "bt2" 变量。

我不断收到此错误消息:

"cannot find symbol bt1" in the e.getSource()==bt1

这是我的代码:

public class ColorChooser extends JFrame implements ActionListener {

    public static void main(String[] args) {
        new ColorChooser();
    }

    public ColorChooser() {
        super("ColorChooser");
        Container content = getContentPane();
        content.setBackground(Color.white);
        content.setLayout(new FlowLayout());
        JRadioButton bt1 = new JRadioButton("Red");
        JRadioButton bt2 = new JRadioButton("Yellow");

        bt1.addActionListener(this);
        bt2.addActionListener(this);
        content.add(bt1);
        content.add(bt2);
        setSize(300, 100);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == bt1)
            getContentPane().setBackground(Color.RED);
        else
            getContentPane().setBackground(Color.YELLOW);
    }
}

在构造函数之外声明 bt1

JRadioButton bt1;

然后在构造函数中初始化

bt1 = new JRadioButton("Red");

您代码中的问题是 bt1 在 constructor.it 声明为块的外部不可见 variable.you 应该声明为实例变量 [在 class 区域]。 示例

public class ColorChooser extends JFrame implements ActionListener {

    JRadioButton bt1;//declare

    public static void main(String[] args) {
        new ColorChooser();
    }

    public ColorChooser() {
        super("ColorChooser");
        Container content = getContentPane();
        content.setBackground(Color.white);
        content.setLayout(new FlowLayout());
        bt1 = new JRadioButton("Red");//initializing
        JRadioButton bt2 = new JRadioButton("Yellow");

        bt1.addActionListener(this);
        bt2.addActionListener(this);
        content.add(bt1);
        content.add(bt2);
        setSize(300, 100);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == bt1) {
            getContentPane().setBackground(Color.RED);
        } else {
            getContentPane().setBackground(Color.YELLOW);
        }

    }

}

您应该将 bt1 声明为实例变量 像那样

public class ColorChooser extends JFrame implements ActionListener
{  
    private JRadioButton bt1;
...
}