java - 找不到 JButton 变量

标签 java swing radio-button awt background-color

我试图在单击单选按钮时更改背景颜色,但编译器找不到第二个单选按钮“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 声明为实例变量 就这样

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

关于java - 找不到 JButton 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709584/

相关文章:

java - 在 JFrame 内创建倒计时器

java - 使用单选按钮组在 Android Studio 中打开新 Activity

javascript - Cypress 单选按钮断言

java - 按下回车键时 JFrame 中的默认按钮未触发

javascript - 从组中获取选定的单选按钮

java - 在 Eclipse 中制作自定义调试 watch 的最简单方法?

java - 如何将 SVN 修订号添加到 MANIFEST 文件中?

Java 泛型值。<SomeValue>

Java - 二进制图像像素索引

java - 如何将 3 个单独的程序放入 JTabbedPane 中。它们已经为 JFrame 编写