我试图在单击单选按钮时更改背景颜色,但编译器找不到第二个单选按钮“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/