import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ColorOptionsPanel extends JPanel { private final int WIDTH = 350, HEIGHT = 100, FONT_SIZE = 20; private final int NUM_COLORS = 5; private Color[] color = new Color[NUM_COLORS]; private JRadioButton[] colorButton = new JRadioButton[NUM_COLORS]; private JLabel heading; // ------------------------------------------------------------------ // Sets up a panel with a label at the top and a set of radio buttons // that control the background color of the panel. // ------------------------------------------------------------------ public ColorOptionsPanel () { heading = new JLabel ("Choose the background color!"); heading.setFont (new Font ("Helvetica", Font.BOLD, FONT_SIZE)); color[0] = Color.yellow; JRadioButton yellow = new JRadioButton("Yellow", true); add(yellow); color[1] = Color.cyan; JRadioButton cyan = new JRadioButton("Cyan", false); add(cyan); color[2] = Color.red; JRadioButton red = new JRadioButton("Red", false); add(red); color[3] = Color.green; JRadioButton green = new JRadioButton("Green", false); add(green); color[4] = Color.magenta; JRadioButton magenta = new JRadioButton("Magneta", false); add(magenta); colorButton[0] = yellow; colorButton[1] = cyan; colorButton[2] = red; colorButton[3] = green; colorButton[4] = magenta; // Instantiate a ButtonGroup object and a ColorListener object ButtonGroup obj = new ButtonGroup(); ColorListener asdf = new ColorListener(); // Set up the panel add (heading); setBackground (Color.yellow); setPreferredSize (new Dimension (WIDTH, HEIGHT)); // Group the radio buttons, add a ColorListener to each obj.add(yellow); yellow.addActionListener(asdf); obj.add(cyan); cyan.addActionListener(asdf); obj.add(red); red.addActionListener(asdf); obj.add(green); green.addActionListener(asdf); obj.add(magenta); magenta.addActionListener(asdf); } // ************************************************************** // Represents the listener for the radio buttons. // ************************************************************** private class ColorListener implements ActionListener { // -------------------------------------------------------- // Updates the background color of the panel based on // which radio button is selected. // -------------------------------------------------------- public void actionPerformed (ActionEvent event) { for(int i=0; i < NUM_COLORS; i++) { if (colorButton[i].isSelected()) { setBackground(color[i]); } } } } }