// @topic T11689 Swing demo A8 -- GUI window with three radio buttons // @brief class GroupRadioButtons extends JPanel, GroupRadioButtonsListener, JRadioButton, ButtonGroup, GridLayout, BorderFactory, Border /** * @author ik */ package pckg; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.text.*; /** * <code>GroupRadioButtons</code> is the JPanel * with two radio buttons. */ public class GroupRadioButtons extends JPanel { // ----- Data Attributes ---------- GroupRadioButtonsListener mRadioListener; JRadioButton mRadioGreen; JRadioButton mRadioBlue; JRadioButton mRadioOrange; ButtonGroup mGroup; //JPanel mPanel; JFrame mFrame; Border mBorder; // ----- Operations ---------- /** * Class constructor takes care of all basic setup steps. */ public GroupRadioButtons(JFrame frame) { mFrame = frame; mRadioListener = new GroupRadioButtonsListener(this); mGroup = new ButtonGroup(); // Create the radio buttons and assign Keyboard shortcuts using Mnemonics mRadioGreen = new JRadioButton("green"); mRadioGreen.setMnemonic(KeyEvent.VK_G); // CTRL+G or ALT+G mRadioGreen.setActionCommand("action_green"); mRadioGreen.setSelected(true); mRadioBlue = new JRadioButton("blue"); mRadioBlue.setMnemonic(KeyEvent.VK_B); // CTRL+B or ALT+B mRadioBlue.setActionCommand("action_blue"); mRadioOrange = new JRadioButton("orange"); mRadioOrange.setMnemonic(KeyEvent.VK_O); // CTRL+O or ALT+O mRadioOrange.setActionCommand("action_orange"); // Group the radio buttons: mGroup.add(mRadioGreen); mGroup.add(mRadioBlue); mGroup.add(mRadioOrange); // Register an action listener for the radio buttons mRadioGreen.addActionListener(mRadioListener); mRadioBlue.addActionListener(mRadioListener); mRadioOrange.addActionListener(mRadioListener); // Put the radio buttons in a column inside a panel this.setLayout(new GridLayout(0, 1)); this.add(mRadioGreen); this.add(mRadioBlue); this.add(mRadioOrange); // Arrange panel border mBorder = BorderFactory.createEtchedBorder(); mBorder = BorderFactory.createTitledBorder(mBorder, "Color Selector"); // adds specified title this.setBorder(mBorder); } // method: GroupRadioButtons /** * Handles user clicks */ public void actionPerformed(ActionEvent event) { Object obj = event.getSource(); if (obj == mRadioGreen) { mFrame.setTitle("Action: " + event.getActionCommand()); } else if (obj == mRadioBlue) { mFrame.setTitle("Action: " + event.getActionCommand()); } else if (obj == mRadioOrange) { mFrame.setTitle("Action: " + event.getActionCommand()); } else { mFrame.setTitle("Action: unknown"); } }//method: actionPerformed /** * Handles user clicks */ public Color getColor() { if (mRadioGreen.isSelected()) { return Color.green; } else if (mRadioBlue.isSelected()) { return Color.blue; } else if (mRadioOrange.isSelected()) { return Color.orange; } return Color.gray; }//method: getColor } // class: GroupRadioButtons