Reputation: 13
I am trying to change the background color on click of a radio button, but the second radio button, "bt2" variable is not found by the compiler.
I keep getting this error message:
"cannot find symbol bt1" in the e.getSource()==bt1
Here is my code:
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);
}
}
Upvotes: 1
Views: 170
Reputation: 9872
declare bt1 outside of constructor
JRadioButton bt1;
then initialize inside constructor
bt1 = new JRadioButton("Red");
the problem in your code is bt1 is not visible to outside of constructor.it's declared as a block variable.you should declare as instance varible [in class area]. example
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);
}
}
}
Upvotes: 1
Reputation: 166
You should declare your bt1 as instance variable Like that
public class ColorChooser extends JFrame implements ActionListener
{
private JRadioButton bt1;
...
}
Upvotes: 2