i'm new to Java, and programming in general.I am trying an exercise where i create radio buttons which change the background colour when selected.At the moment i am using Eclipse IDE.
Eclipse is not giving me any errors and i can run the b/m program just fine, with the radiobuttons showing up and being clickable.However, the radio buttons fail to change the background colour when i select them. I would appreciate any answers and pointers i can get.
Thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Gui{
//Declares Variables
JRadioButton red=new JRadioButton("red");
JRadioButton blue=new JRadioButton("blue");
JRadioButton yellow=new JRadioButton("yellow");
ButtonGroup group = new ButtonGroup();
//Constructor
public Gui(){
//Sets title
super("RadioButton Exercise");
//Sets layout as default
setLayout(new FlowLayout());
//Adds the JRadioButtons
add(red);
add(blue);
add(yellow);
//Groups the variables
group.add(red);
group.add(blue);
group.add(yellow);
//Creates HandlerClass object
HandlerClass handler = new HandlerClass();
//When buttons are clicked, HandlerClass is called
red.addItemListener(handler);
blue.addItemListener(handler);
yellow.addItemListener(handler);
}
public class HandlerClass implements ItemListener{
public void itemStateChanged(ItemEvent x){
if(x.getSource()==red){
setBackground(Color.RED);
}
else if(x.getSource()==blue){
setBackground(Color.BLUE);
}
else{
setBackground(Color.YELLOW);
}
}
}
}