Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*ColorChangeTest.java*/
- import javax.swing.JFrame;
- import java.awt.Dimension;
- public class ColorChangeTest{
- public static void main( String[] args ){
- ColorChange colorChange = new ColorChange();
- colorChange.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
- colorChange.setVisible( true );
- Dimension minimumSize = new Dimension( 400, 200 );
- colorChange.setMinimumSize( minimumSize );
- colorChange.pack();
- }//end of main
- }//end of class
- /*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{
- //declare button variables
- 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());//set layout
- //radio buttons
- redButton = new JRadioButton( "Red", true );
- blueButton = new JRadioButton( "Blue", false );
- greenButton = new JRadioButton( "Green", false );
- magentaButton = new JRadioButton( "Magenta", false );
- //add to JFrame
- add( redButton );
- add( blueButton );
- add( greenButton );
- add( magentaButton );
- //add to the buttongroup
- radioGroup = new ButtonGroup();
- radioGroup.add( redButton );
- radioGroup.add( blueButton );
- radioGroup.add( greenButton );
- radioGroup.add( magentaButton );
- //register events
- redButton.addItemListener(new RadioButtonHandler(Color.RED));
- blueButton.addItemListener(new RadioButtonHandler(Color.BLUE));
- greenButton.addItemListener(new RadioButtonHandler(Color.GREEN));
- magentaButton.addItemListener(new RadioButtonHandler(Color.MAGENTA));
- //set the initial red colour
- getContentPane().setBackground( Color.RED );
- }//end of constructor
- //handling events
- private class RadioButtonHandler implements ItemListener{
- private Color colour;
- public RadioButtonHandler( Color targetColour){//constructor taking a color object
- colour = targetColour;
- }//end of constructor
- public void itemStateChanged( ItemEvent event ){
- getContentPane().setBackground( colour );
- }//end of method
- }//end of inner class
- }//end of class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement