/* Author: Jeff Dalton * Updated: Fri Jul 13 23:22:36 2001 by Jeff Dalton * Copyright: (c) 2001, AIAI, University of Edinburgh */ package ix.iface.util; import javax.swing.*; import java.awt.event.*; import java.awt.Component; /** * An object that manages a group of radio buttons in a convenient * and easy to use fashion.

* * Essentially it is a JPanel with a BoxLayout, and components of all * sorts can be added to it; however, if a JRadioButton is added, the * button is to a ButtonGroup and given an ActionListener that records * its action command when it is selected. The most recently selected * action command can be obtained by calling the getSelection * method. */ public class RadioButtonBox extends JPanel { protected ButtonGroup group = new ButtonGroup(); protected String selection = null; /** The listener this box attaches to radio buttons. */ protected ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent event) { selection = event.getActionCommand(); } }; /** * Creates a box that places components along the specified axis. * * @param axis either BoxLayout.X_AXIS or * BoxLayout.Y_AXIS for a horizontal or * vertical box respectively. */ public RadioButtonBox(int axis) { setLayout(new BoxLayout(this, axis)); } /** * Creates a RadioButtonBox that arranges components from left to right. */ public static RadioButtonBox createHorizontalBox() { return new RadioButtonBox(BoxLayout.X_AXIS); } /** * Creates a RadioButtonBox that arranges components from top to bottom. */ public static RadioButtonBox createVerticalBox() { return new RadioButtonBox(BoxLayout.Y_AXIS); } /** * Returns the action command specified by the most recently * selected JRadioButton in the box. */ public String getSelection() { return selection; } protected void addImpl(Component comp, Object constraints, int index) { if (comp instanceof JRadioButton) { JRadioButton button = (JRadioButton)comp; group.add(button); button.addActionListener(listener); if (button.isSelected()) selection = button.getActionCommand(); } super.addImpl(comp, constraints, index); } }