找不到JButton变量

阿克沙特·马尔维娅(Akshat Malviya)

我试图在单击单选按钮时更改背景颜色,但是编译器未找到第二个单选按钮“ 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);
    }
}
Madhawa Priyashantha

在构造函数外部声明bt1

JRadioButton bt1;

然后在构造函数中初始化

bt1 = new JRadioButton("Red");

代码中的问题是bt1在构造函数外部不可见。它声明为块变量。您应该在[类区域]中声明为实例变量。例子

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

    }

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章