/** * The code in this file displays a set of 3 JRadioButtons. When one is clicked, * the background is changed appropriately and a JLabel that shows * the currently selected color is updated. * * @author John Paxton * @version 1.0 */ import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import javax.swing.JLabel; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class MyPanel extends JPanel { /** * Class constructor. */ MyPanel() { currentBackground = Color.red; colorGroup = new ButtonGroup(); add (new MyButton("Blue", this, Color.blue, colorGroup)); add (new MyButton("Yellow", this, Color.yellow, colorGroup)); add (new MyButton("Green", this, Color.green, colorGroup)); add (new JLabel("Color Selected: ")); selectedLabel = new JLabel("Unselected"); add (selectedLabel); } // An inner class. class MyButton extends JRadioButton implements ActionListener { /** * Class constructor for a custom JRadioButton. * * @author John Paxton * @version 1.01, 01-23-2006 * * @param label the label for the button * @param parent the JPanel in which this button resides * @param background the color to set the background of the JPanel * @param group the logical group to which this JRadioButton belongs */ MyButton (String label, MyPanel parent, Color background, ButtonGroup group) { group.add(this); setContentAreaFilled(false); setText(label); addActionListener(this); this.parent = parent; color = background; } /** * Specifies what to do when a JRadioButton is clicked. * * @param evt the event that occurred */ public void actionPerformed (ActionEvent evt) { currentBackground = color; selectedLabel.setText(evt.getActionCommand()); parent.repaint(); } /** * Adds one to the parameter passed into it. * * @param n a number to add one to * @return the new number */ public int addOne (int n) { return n + 1; } private MyPanel parent; // the JPanel that contains this JRadioButton private Color color; // the desired background for the containing JPanel } /** * Displays the appropriate information in the JPanel * * @param g the drawing object */ public void paintComponent (Graphics g) { super.paintComponent(g); setBackground(currentBackground); } private Color currentBackground; // current background of JPanel private ButtonGroup colorGroup; // to logically organize the color JRadioButtons private JLabel selectedLabel; // shows the currently selected color }