public class RadioButtonTest
{
public static void main(String[] args)
{
RadioButtonFrame frame = new RadioButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
/**
* A frame with a sample text label and radio buttons for selecting font sizes.
*/
class RadioButtonFrame extends JFrame
{
public RadioButtonFrame()
{
setTitle("RadioButtonTest");
setSize(WIDTH, HEIGHT);
Container contentPane = getContentPane();
// add the sample text label
label = new JLabel("The quick brown fox jumps over the lazy dog");
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
contentPane.add(label, BorderLayout.CENTER);
// add the radio buttons
buttonPanel = new JPanel();
group = new ButtonGroup();
/**
* Adds a radio button that sets the font size of the sample text.
* @param name the string to appear on the button
* @param size the font size that this button sets
*/
public void addRadioButton(String name, final int size)
{
boolean selected = (size == DEFAULT_SIZE);
JRadioButton button = new JRadioButton(name, selected);
group.add(button);
buttonPanel.add(button);
// this lisetner sets the label font size
ActionListener listener = new
ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
// size refers to the final parameter of the addRadioButton method
label.setFont(new Font("serif", Font.PLAIN, size));
}
};
button.addActionListener(listener);
}
public static final int WIDTH = 400;
public static final int HEIGHT = 200;
private JPanel buttonPanel;
private ButtonGroup group;
private JLabel label;
private static final int DEFAULT_SIZE = 12;
}