Set action command for JRadioButton in Java

Description

The following code shows how to set action command for JRadioButton.

Example


//w ww.  j a  va 2s. co m

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());
  }
}

The code above generates the following result.

Set action command for JRadioButton in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer