Academic Java    Java Tutorial  >  Swing  >  JRadioButton

JRadioButton Example

Java JRadioButton EXAMPLE output This JRadioButton example lays out radio buttons vertically in a panel.

Each JRadioButton has to be added to a ButtonGroup to ensure only one is selected at a time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// JRadioButton Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class JRadioButtonExample {

   public static void main(String[] args) {

      ActionListener listener = new ActionListener() {
         public void actionPerformed (ActionEvent e) {
            System.out.println(e.getActionCommand());
         }
      };

      Box p = new Box(BoxLayout.Y_AXIS);
      ButtonGroup group = new ButtonGroup();
      String[] sa = {"ugli","kiwi","passion","kumquat"};

      for(int i=0;i<sa.length;++i) {
         JRadioButton b = new JRadioButton(sa[i]);
         group.add(b);
         p.add(b);
         b.addActionListener(listener);
      }

      JFrame frame = new JFrame("Fruits");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(p);
      frame.pack();
      frame.setVisible(true);
   }
}

21 This constructor takes the text for the JRadioButton as a parameter. The possble constructors are:
	JRadioButton()
	JRadioButton(Action a)
	JRadioButton(Icon icon)
	JRadioButton(Icon icon, boolean selected)
	JRadioButton(String text)
	JRadioButton(String text, boolean selected)
	JRadioButton(String text, Icon icon)
	JRadioButton(String text, Icon icon, boolean selected)
which shows that icons can be used and that button/s can be pre-selected.

* JRadioButton Examples