Implement group of buttons in an application : Radio Button « Swing JFC « Java






Implement group of buttons in an application

  

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

   
    
  








Related examples in the same category

1.Creating a JRadioButton Component
2.Radio Button Mnemonic KeyRadio Button Mnemonic Key
3.Using JRadioButtonsUsing JRadioButtons
4.A ButtonGroup voting boothA ButtonGroup voting booth
5.RadioButton DemoRadioButton Demo
6.React Radio button eventReact Radio button event
7.Working with the JRadioButtonWorking with the JRadioButton
8.ButtonGroup DemoButtonGroup Demo
9.Group RadioButtonGroup RadioButton
10.Group Action RadioButtonGroup Action RadioButton
11.Selecting a JRadioButton Component in a Button Group
12.A frame with a sample text label and radio buttons for selecting font sizesA frame with a sample text label and radio buttons for selecting font sizes