Hi guys, I run into a problem. I am trying to write a small program. There should be 4 radio buttons and each of them controls the colour of the Content Pane.
The problem I have is with the anonymous inner class (I hear JamesCherrill muttering "why do you bother?", but hey!) and essentially I don't know how to attach the handlers - because I need to have multiple
radio buttons. If I didn't use the anonymous class I would do this:
redButton.addItemListener(new RadioButtonHandler(Color.RED));
blueButton.addItemListener(new RadioButtonHandler(Color.BLUE));
greenButton.addItemListener(new RadioButtonHandler(Color.GREEN));
magentaButton.addItemListener(new RadioButtonHandler(Color.MAGENTA));
but how do I do that with an anonymous class?
Is this allowed:
redButton.addItemListener(
new ItemListener(
...
)
)
blueButton.addItemListener(
new ItemListener(
...
)
)
greenButton.addItemListener(
new ItemListener(
...
)
)
magentaButton.addItemListener(
new ItemListener(
...
)
)
I am not sure if I can do that, so for now I only have a basic version if you like:
/*ColorChange.java*/
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.JFrame;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
public class ColorChange extends JFrame{
private JRadioButton redButton;
private JRadioButton blueButton;
private JRadioButton greenButton;
private JRadioButton magentaButton;
private ButtonGroup radioGroup;
//use example of font
public ColorChange(){
super("colours test");
setlayout( new FlowLayout());
//radio buttons
redButton = new JRadioButton( "Red", true );
blueButton = new JRadioButton( "Blue", false );
greenButton = new JRadioButton( "Green", false );
magentaButton = new JRadioButton( "Magenta", false );
add( redButton );
add( blueButton );
add( greenButton );
add( magentaButton );
radioGroup = new ButtonGroup();
radioGroup.add( redButton );
radioGroup.add( blueButton );
radioGroup.add( greenButton );
radioGroup.add( magentaButton );
}//end of constructor
}//end of class
Cheers