Reputation: 1433
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);
}
}
}
}
Upvotes: 0
Views: 152
Reputation: 159804
Assuming that you meant
public class Gui extends JFrame {
It's not that the JRadioButton
that is not responding, the problem is that setBackGround
is being called on the frame directly, rather than it's visible component, i.e. the ContentPane
. You can use:
getContentPane().setBackground(Color.RED);
Upvotes: 2
Reputation: 13334
You have conditions like x.getSource()==red
. It does not compare objects
; it compares object references
. So even if two different object references point to the same object such expression will yield False
.
If you want to compare objects you need to use equals
method. For equal
to produce meaningful result the two objects should be of the same type.
I suggest the following: (JradioButton)x.getSource().equals(red);
Upvotes: 0