Java/Swing JFC/Radio Button
Содержание
- 1 A ButtonGroup voting booth
- 2 ButtonGroup Demo
- 3 Creating a JRadioButton Component
- 4 Group Action RadioButton
- 5 Group RadioButton
- 6 Implement group of buttons in an application
- 7 RadioButton Demo
- 8 Radio Button Mnemonic Key
- 9 React Radio button event
- 10 Selecting a JRadioButton Component in a Button Group
- 11 Using JRadioButtons
- 12 Working with the JRadioButton
A ButtonGroup voting booth
<source lang="java">
/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly
- /
// SimpleButtonGroupExample.java //A ButtonGroup voting booth. // import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JRadioButton; public class SimpleButtonGroupExample {
public static void main(String[] args) { // Some choices JRadioButton choice1, choice2, choice3; choice1 = new JRadioButton("Bach: Well Tempered Clavier, Book I"); choice1.setActionCommand("bach1"); choice2 = new JRadioButton("Bach: Well Tempered Clavier, Book II"); choice2.setActionCommand("bach2"); choice3 = new JRadioButton("Shostakovich: 24 Preludes and Fugues"); choice3.setActionCommand("shostakovich"); // A group, to ensure that we only vote for one. final ButtonGroup group = new ButtonGroup(); group.add(choice1); group.add(choice2); group.add(choice3); // A simple ActionListener, showing each selection using the ButtonModel class VoteActionListener implements ActionListener { public void actionPerformed(ActionEvent ev) { String choice = group.getSelection().getActionCommand(); System.out.println("ACTION Choice Selected: " + choice); } } // A simple ItemListener, showing each selection and deselection class VoteItemListener implements ItemListener { public void itemStateChanged(ItemEvent ev) { boolean selected = (ev.getStateChange() == ItemEvent.SELECTED); AbstractButton button = (AbstractButton) ev.getItemSelectable(); System.out.println("ITEM Choice Selected: " + selected + ", Selection: " + button.getActionCommand()); } } // Add listeners to each button ActionListener alisten = new VoteActionListener(); choice1.addActionListener(alisten); choice2.addActionListener(alisten); choice3.addActionListener(alisten); ItemListener ilisten = new VoteItemListener(); choice1.addItemListener(ilisten); choice2.addItemListener(ilisten); choice3.addItemListener(ilisten); // Throw everything together JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = frame.getContentPane(); c.setLayout(new GridLayout(0, 1)); c.add(new JLabel("Vote for your favorite prelude & fugue cycle")); c.add(choice1); c.add(choice2); c.add(choice3); frame.pack(); frame.setVisible(true); }
}
</source>
ButtonGroup Demo
<source lang="java">
import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JRadioButtonMenuItem; import javax.swing.JToggleButton; import javax.swing.border.Border; public class AButtonGroup {
public static void main(String args[]) { JFrame frame = new JFrame("Button Group"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new GridLayout(0, 1)); Border border = BorderFactory.createTitledBorder("Examples"); panel.setBorder(border); ButtonGroup group = new ButtonGroup(); AbstractButton abstract1 = new JToggleButton("Toggle Button"); panel.add(abstract1); group.add(abstract1); AbstractButton abstract2 = new JRadioButton("Radio Button"); panel.add(abstract2); group.add(abstract2); AbstractButton abstract3 = new JCheckBox("Check Box"); panel.add(abstract3); group.add(abstract3); AbstractButton abstract4 = new JRadioButtonMenuItem( "Radio Button Menu Item"); panel.add(abstract4); group.add(abstract4); AbstractButton abstract5 = new JCheckBoxMenuItem("Check Box Menu Item"); panel.add(abstract5); group.add(abstract5); Container contentPane = frame.getContentPane(); contentPane.add(panel, BorderLayout.CENTER); frame.setSize(300, 200); frame.setVisible(true); }
}
</source>
Creating a JRadioButton Component
<source lang="java">
import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ButtonGroup; import javax.swing.JRadioButton; public class Main {
public static void main(String[] argv) throws Exception { Action action1 = new AbstractAction("RadioButton Label1") { public void actionPerformed(ActionEvent evt) { } }; Action action2 = new AbstractAction("RadioButton Label2") { public void actionPerformed(ActionEvent evt) { } }; JRadioButton b1 = new JRadioButton(action1); JRadioButton b2 = new JRadioButton(action2); ButtonGroup group = new ButtonGroup(); group.add(b1); group.add(b2); }
}
</source>
Group Action RadioButton
<source lang="java">
/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress
- /
import java.awt.BorderLayout; import java.awt.ruponent; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Enumeration; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class GroupActionRadio {
private static final String sliceOptions[] = { "4 slices", "8 slices", "12 slices", "16 slices" }; private static final String crustOptions[] = { "Sicilian", "Thin Crust", "Thick Crust", "Stuffed Crust" }; public static void main(String args[]) { String title = (args.length == 0 ? "Grouping Example" : args[0]); JFrame frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Slice Parts ActionListener sliceActionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { AbstractButton aButton = (AbstractButton) actionEvent .getSource(); System.out.println("Selected: " + aButton.getText()); } }; Container sliceContainer = RadioButtonUtils.createRadioButtonGrouping( sliceOptions, "Slice Count", sliceActionListener); // Crust Parts ActionListener crustActionListener = new ActionListener() { String lastSelected; public void actionPerformed(ActionEvent actionEvent) { AbstractButton aButton = (AbstractButton) actionEvent .getSource(); String label = aButton.getText(); String msgStart; if (label.equals(lastSelected)) { msgStart = "Reselected: "; } else { msgStart = "Selected: "; } lastSelected = label; System.out.println(msgStart + label); } }; ItemListener itemListener = new ItemListener() { String lastSelected; public void itemStateChanged(ItemEvent itemEvent) { AbstractButton aButton = (AbstractButton) itemEvent.getSource(); int state = itemEvent.getStateChange(); String label = aButton.getText(); String msgStart; if (state == ItemEvent.SELECTED) { if (label.equals(lastSelected)) { msgStart = "Reselected -> "; } else { msgStart = "Selected -> "; } lastSelected = label; } else { msgStart = "Deselected -> "; } System.out.println(msgStart + label); } }; ChangeListener changeListener = new ChangeListener() { public void stateChanged(ChangeEvent changEvent) { AbstractButton aButton = (AbstractButton) changEvent .getSource(); ButtonModel aModel = aButton.getModel(); boolean armed = aModel.isArmed(); boolean pressed = aModel.isPressed(); boolean selected = aModel.isSelected(); System.out.println("Changed: " + armed + "/" + pressed + "/" + selected); } }; final Container crustContainer = RadioButtonUtils .createRadioButtonGrouping(crustOptions, "Crust Type", crustActionListener, itemListener, changeListener); // Button Parts ActionListener buttonActionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { Enumeration selected = RadioButtonUtils .getSelectedElements(crustContainer); while (selected.hasMoreElements()) { System.out.println("Selected -> " + selected.nextElement()); } } }; JButton button = new JButton("Order Pizza"); button.addActionListener(buttonActionListener); Container contentPane = frame.getContentPane(); contentPane.add(sliceContainer, BorderLayout.WEST); contentPane.add(crustContainer, BorderLayout.EAST); contentPane.add(button, BorderLayout.SOUTH); frame.setSize(300, 200); frame.setVisible(true); }
} class RadioButtonUtils {
private RadioButtonUtils() { // private constructor so you can"t create instances } public static Enumeration getSelectedElements(Container container) { Vector selections = new Vector(); Component components[] = container.getComponents(); for (int i = 0, n = components.length; i < n; i++) { if (components[i] instanceof AbstractButton) { AbstractButton button = (AbstractButton) components[i]; if (button.isSelected()) { selections.addElement(button.getText()); } } } return selections.elements(); } public static Container createRadioButtonGrouping(String elements[]) { return createRadioButtonGrouping(elements, null, null, null, null); } public static Container createRadioButtonGrouping(String elements[], String title) { return createRadioButtonGrouping(elements, title, null, null, null); } public static Container createRadioButtonGrouping(String elements[], String title, ItemListener itemListener) { return createRadioButtonGrouping(elements, title, null, itemListener, null); } public static Container createRadioButtonGrouping(String elements[], String title, ActionListener actionListener) { return createRadioButtonGrouping(elements, title, actionListener, null, null); } public static Container createRadioButtonGrouping(String elements[], String title, ActionListener actionListener, ItemListener itemListener) { return createRadioButtonGrouping(elements, title, actionListener, itemListener, null); } public static Container createRadioButtonGrouping(String elements[], String title, ActionListener actionListener, ItemListener itemListener, ChangeListener changeListener) { JPanel panel = new JPanel(new GridLayout(0, 1)); // If title set, create titled border if (title != null) { Border border = BorderFactory.createTitledBorder(title); panel.setBorder(border); } // Create group ButtonGroup group = new ButtonGroup(); JRadioButton aRadioButton; // For each String passed in: // Create button, add to panel, and add to group for (int i = 0, n = elements.length; i < n; i++) { aRadioButton = new JRadioButton(elements[i]); panel.add(aRadioButton); group.add(aRadioButton); if (actionListener != null) { aRadioButton.addActionListener(actionListener); } if (itemListener != null) { aRadioButton.addItemListener(itemListener); } if (changeListener != null) { aRadioButton.addChangeListener(changeListener); } } return panel; }
}
</source>
Group RadioButton
<source lang="java">
/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress
- /
import java.awt.BorderLayout; import java.awt.ruponent; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionListener; import java.awt.event.ItemListener; import java.util.Enumeration; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.border.Border; import javax.swing.event.ChangeListener; public class GroupRadio {
private static final String sliceOptions[] = { "4 slices", "8 slices", "12 slices", "16 slices" }; private static final String crustOptions[] = { "Sicilian", "Thin Crust", "Thick Crust", "Stuffed Crust" }; public static void main(String args[]) { JFrame frame = new JFrame("Grouping Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container sliceContainer = RadioButtonUtils.createRadioButtonGrouping( sliceOptions, "Slice Count"); Container crustContainer = RadioButtonUtils.createRadioButtonGrouping( crustOptions, "Crust Type"); Container contentPane = frame.getContentPane(); contentPane.add(sliceContainer, BorderLayout.WEST); contentPane.add(crustContainer, BorderLayout.EAST); frame.setSize(300, 200); frame.setVisible(true); }
} class RadioButtonUtils {
private RadioButtonUtils() { // private constructor so you can"t create instances } public static Enumeration getSelectedElements(Container container) { Vector selections = new Vector(); Component components[] = container.getComponents(); for (int i = 0, n = components.length; i < n; i++) { if (components[i] instanceof AbstractButton) { AbstractButton button = (AbstractButton) components[i]; if (button.isSelected()) { selections.addElement(button.getText()); } } } return selections.elements(); } public static Container createRadioButtonGrouping(String elements[]) { return createRadioButtonGrouping(elements, null, null, null, null); } public static Container createRadioButtonGrouping(String elements[], String title) { return createRadioButtonGrouping(elements, title, null, null, null); } public static Container createRadioButtonGrouping(String elements[], String title, ItemListener itemListener) { return createRadioButtonGrouping(elements, title, null, itemListener, null); } public static Container createRadioButtonGrouping(String elements[], String title, ActionListener actionListener) { return createRadioButtonGrouping(elements, title, actionListener, null, null); } public static Container createRadioButtonGrouping(String elements[], String title, ActionListener actionListener, ItemListener itemListener) { return createRadioButtonGrouping(elements, title, actionListener, itemListener, null); } public static Container createRadioButtonGrouping(String elements[], String title, ActionListener actionListener, ItemListener itemListener, ChangeListener changeListener) { JPanel panel = new JPanel(new GridLayout(0, 1)); // If title set, create titled border if (title != null) { Border border = BorderFactory.createTitledBorder(title); panel.setBorder(border); } // Create group ButtonGroup group = new ButtonGroup(); JRadioButton aRadioButton; // For each String passed in: // Create button, add to panel, and add to group for (int i = 0, n = elements.length; i < n; i++) { aRadioButton = new JRadioButton(elements[i]); panel.add(aRadioButton); group.add(aRadioButton); if (actionListener != null) { aRadioButton.addActionListener(actionListener); } if (itemListener != null) { aRadioButton.addItemListener(itemListener); } if (changeListener != null) { aRadioButton.addChangeListener(changeListener); } } return panel; }
}
</source>
Implement group of buttons in an application
<source lang="java">
import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JRadioButton; public class Main {
public static void main(String[] args) { JRadioButton choice1, choice2, choice3; choice1 = new JRadioButton("A"); choice1.setActionCommand("A"); choice2 = new JRadioButton("B"); choice2.setActionCommand("B"); choice3 = new JRadioButton("C"); choice3.setActionCommand("C"); final ButtonGroup group = new ButtonGroup(); group.add(choice1); group.add(choice2); group.add(choice3); class VoteActionListener implements ActionListener { public void actionPerformed(ActionEvent ev) { System.out.println(group.getSelection().getActionCommand()); } } ActionListener alisten = new VoteActionListener(); choice1.addActionListener(alisten); choice2.addActionListener(alisten); choice3.addActionListener(alisten); ItemListener ilisten = new VoteItemListener(); choice1.addItemListener(ilisten); choice2.addItemListener(ilisten); choice3.addItemListener(ilisten); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = frame.getContentPane(); c.setLayout(new GridLayout(0, 1)); c.add(choice1); c.add(choice2); c.add(choice3); frame.pack(); frame.setVisible(true); }
}
class VoteItemListener implements ItemListener {
public void itemStateChanged(ItemEvent ev) { boolean selected = (ev.getStateChange() == ItemEvent.SELECTED); AbstractButton button = (AbstractButton) ev.getItemSelectable(); System.out.println(selected + ", Selection: " + button.getActionCommand()); }
}
</source>
RadioButton Demo
<source lang="java">
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JRadioButtonMenuItem; public class RadioButtonSample {
static Icon threeIcon = new ImageIcon("3.gif"); static Icon fourIcon = new ImageIcon("4.gif"); static Icon fiveIcon = new ImageIcon("5.gif"); static Icon sixIcon = new ImageIcon("6.gif"); public static void main(String args[]) { ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { AbstractButton aButton = (AbstractButton) actionEvent .getSource(); boolean selected = aButton.getModel().isSelected(); System.out.println(actionEvent.getActionCommand() + " - selected? " + selected); } }; ItemListener itemListener = new ItemListener() { public void itemStateChanged(ItemEvent itemEvent) { AbstractButton aButton = (AbstractButton) itemEvent.getSource(); int state = itemEvent.getStateChange(); String selected = ((state == ItemEvent.SELECTED) ? "selected" : "not selected"); System.out.println(aButton.getText() + " - selected? " + selected); } }; JFrame frame = new JFrame("Radio Menu Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("Menu"); ButtonGroup buttonGroup = new ButtonGroup(); menu.setMnemonic(KeyEvent.VK_M); JRadioButtonMenuItem emptyMenuItem = new JRadioButtonMenuItem(); emptyMenuItem.setActionCommand("Empty"); emptyMenuItem.addActionListener(actionListener); buttonGroup.add(emptyMenuItem); menu.add(emptyMenuItem); JRadioButtonMenuItem oneMenuItem = new JRadioButtonMenuItem("Partridge"); oneMenuItem.addActionListener(actionListener); buttonGroup.add(oneMenuItem); menu.add(oneMenuItem); JRadioButtonMenuItem twoMenuItem = new JRadioButtonMenuItem( "Turtle Doves", true); twoMenuItem.addActionListener(actionListener); buttonGroup.add(twoMenuItem); menu.add(twoMenuItem); JRadioButtonMenuItem threeMenuItem = new JRadioButtonMenuItem( "French Hens", threeIcon); threeMenuItem.addItemListener(itemListener); buttonGroup.add(threeMenuItem); menu.add(threeMenuItem); JRadioButtonMenuItem fourMenuItem = new JRadioButtonMenuItem( "Calling Birds", fourIcon, true); fourMenuItem.addActionListener(actionListener); buttonGroup.add(fourMenuItem); menu.add(fourMenuItem); JRadioButtonMenuItem fiveMenuItem = new JRadioButtonMenuItem(fiveIcon); fiveMenuItem.addActionListener(actionListener); fiveMenuItem.setActionCommand("Rings"); buttonGroup.add(fiveMenuItem); menu.add(fiveMenuItem); JRadioButtonMenuItem sixMenuItem = new JRadioButtonMenuItem(sixIcon, true); sixMenuItem.addActionListener(actionListener); sixMenuItem.setActionCommand("Geese"); buttonGroup.add(sixMenuItem); menu.add(sixMenuItem); menuBar.add(menu); frame.setJMenuBar(menuBar); frame.setSize(350, 250); frame.setVisible(true); }
}
</source>
Radio Button Mnemonic Key
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; /*
* RadioButtonDemo.java is a 1.4 application that requires these files: * images/Bird.gif images/Cat.gif images/Dog.gif images/Rabbit.gif * images/Pig.gif */
public class RadioButtonDemo extends JPanel implements ActionListener {
static String birdString = "Bird"; static String catString = "Cat"; static String dogString = "Dog"; static String rabbitString = "Rabbit"; static String pigString = "Pig"; JLabel picture; public RadioButtonDemo() { super(new BorderLayout()); //Create the radio buttons. JRadioButton birdButton = new JRadioButton(birdString); birdButton.setMnemonic(KeyEvent.VK_B); birdButton.setActionCommand(birdString); birdButton.setSelected(true); JRadioButton catButton = new JRadioButton(catString); catButton.setMnemonic(KeyEvent.VK_C); catButton.setActionCommand(catString); JRadioButton dogButton = new JRadioButton(dogString); dogButton.setMnemonic(KeyEvent.VK_D); dogButton.setActionCommand(dogString); JRadioButton rabbitButton = new JRadioButton(rabbitString); rabbitButton.setMnemonic(KeyEvent.VK_R); rabbitButton.setActionCommand(rabbitString); JRadioButton pigButton = new JRadioButton(pigString); pigButton.setMnemonic(KeyEvent.VK_P); pigButton.setActionCommand(pigString); //Group the radio buttons. ButtonGroup group = new ButtonGroup(); group.add(birdButton); group.add(catButton); group.add(dogButton); group.add(rabbitButton); group.add(pigButton); //Register a listener for the radio buttons. birdButton.addActionListener(this); catButton.addActionListener(this); dogButton.addActionListener(this); rabbitButton.addActionListener(this); pigButton.addActionListener(this); //Set up the picture label. picture = new JLabel(createImageIcon("images/" + birdString + ".gif")); //The preferred size is hard-coded to be the width of the //widest image and the height of the tallest image. //A real program would compute this. picture.setPreferredSize(new Dimension(177, 122)); //Put the radio buttons in a column in a panel. JPanel radioPanel = new JPanel(new GridLayout(0, 1)); radioPanel.add(birdButton); radioPanel.add(catButton); radioPanel.add(dogButton); radioPanel.add(rabbitButton); radioPanel.add(pigButton); add(radioPanel, BorderLayout.LINE_START); add(picture, BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); } /** Listens to the radio buttons. */ public void actionPerformed(ActionEvent e) { picture.setIcon(createImageIcon("images/" + e.getActionCommand() + ".gif")); } /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = RadioButtonDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn"t find file: " + path); return null; } } /** * Create the GUI and show it. For thread safety, this method should be * invoked from the event-dispatching thread. */ private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("RadioButtonDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. JComponent newContentPane = new RadioButtonDemo(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application"s GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }
}
</source>
React Radio button event
<source lang="java">
import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; public class RadioButtonTest extends JFrame implements ActionListener {
JLabel label = new JLabel("The quick brown fox jumps over the lazy dog."); private JRadioButton smallButton; private JRadioButton mediumButton; private JRadioButton largeButton; private JRadioButton xlargeButton; public RadioButtonTest() { setTitle("RadioButtonTest"); setSize(400, 200); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); JPanel buttonPanel = new JPanel(); ButtonGroup group = new ButtonGroup(); smallButton = addRadioButton(buttonPanel, group, "Small", false); mediumButton = addRadioButton(buttonPanel, group, "Medium", true); largeButton = addRadioButton(buttonPanel, group, "Large", false); xlargeButton = addRadioButton(buttonPanel, group, "Extra large", false); getContentPane().add(buttonPanel, "South"); getContentPane().add(label, "Center"); } public JRadioButton addRadioButton(JPanel buttonPanel, ButtonGroup g, String buttonName, boolean v) { JRadioButton button = new JRadioButton(buttonName, v); button.addActionListener(this); g.add(button); buttonPanel.add(button); return button; } public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source == smallButton) label.setFont(new Font("SansSerif", Font.PLAIN, 8)); else if (source == mediumButton) label.setFont(new Font("SansSerif", Font.PLAIN, 12)); else if (source == largeButton) label.setFont(new Font("SansSerif", Font.PLAIN, 14)); else if (source == xlargeButton) label.setFont(new Font("SansSerif", Font.PLAIN, 18)); } public static void main(String[] args) { JFrame frame = new RadioButtonTest(); frame.show(); }
}
</source>
Selecting a JRadioButton Component in a Button Group
<source lang="java">
import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.JRadioButton; public class Main {
public static void main(String[] argv) throws Exception { JRadioButton radioButton = new JRadioButton(); ButtonGroup group = new ButtonGroup(); ButtonModel model = radioButton.getModel(); group.setSelected(model, true); }
}
</source>
Using JRadioButtons
<source lang="java">
// : c14:SwingRadioButtons.java // Using JRadioButtons. // <applet code=SwingRadioButtons width=200 height=100></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JApplet; import javax.swing.JFrame; import javax.swing.JRadioButton; import javax.swing.JTextField; public class SwingRadioButtons extends JApplet {
private JTextField t = new JTextField(15); private ButtonGroup g = new ButtonGroup(); private JRadioButton rb1 = new JRadioButton("one", false), rb2 = new JRadioButton("two", false), rb3 = new JRadioButton( "three", false); private ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e) { t.setText("Radio button " + ((JRadioButton) e.getSource()).getText()); } }; public void init() { rb1.addActionListener(al); rb2.addActionListener(al); rb3.addActionListener(al); g.add(rb1); g.add(rb2); g.add(rb3); t.setEditable(false); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(t); cp.add(rb1); cp.add(rb2); cp.add(rb3); } public static void main(String[] args) { run(new SwingRadioButtons(), 200, 100); } public static void run(JApplet applet, int width, int height) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(applet); frame.setSize(width, height); applet.init(); applet.start(); frame.setVisible(true); }
} ///:~
</source>
Working with the JRadioButton
<source lang="java">
import java.awt.Container; import java.awt.GridLayout; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JRadioButton; public class SwingRadioButtonTest {
public static void main(String args[]) { JFrame frame = new JFrame(); Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridLayout(0, 1)); ButtonGroup group = new ButtonGroup(); JRadioButton option = new JRadioButton("French Fries", true); group.add(option); contentPane.add(option); option = new JRadioButton("Onion Rings", false); group.add(option); contentPane.add(option); option = new JRadioButton("Ice Cream", false); group.add(option); contentPane.add(option); frame.setSize(200, 200); frame.show(); }
}
</source>