Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the Button Group Swing control in Java?

How do I add radio buttons to a button group using NetBeans?

Once I add them, how do I get selected radio button from the button group?

like image 779
Venkat Avatar asked Feb 20 '10 05:02

Venkat


People also ask

What is the use of button group in Java?

This class is used to create a multiple-exclusion scope for a set of buttons. Creating a set of buttons with the same ButtonGroup object means that turning "on" one of those buttons turns off all other buttons in the group. A ButtonGroup can be used with any set of objects that inherit from AbstractButton .

Which control is used with button group?

A button group is a container control that holds push button controls. The button group defines the layout for the buttons it contains, including alignment within the container and the title for the group. Place this control within a section control or a table control.


2 Answers

  1. Drag a ButtonGroup from the palette and drop it on your GUI. It will show up under Other Components in the Inspector panel.
  2. Right-click on it and Change variable name to something meaningful.
  3. Now select a radio button in your GUI.
  4. In the Properties panel look for the buttonGroup property.
  5. Click the combo box next to it and select your button group.
like image 125
Devon_C_Miller Avatar answered Oct 02 '22 05:10

Devon_C_Miller


I highly recommend reading this excellent tutorial. Here's an excerpt of code from the article that satisfies your question on how to create and add buttons to a ButtonGroup:

JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setSelected(true);

JRadioButton catButton = new JRadioButton(catString);

   //Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);

As far as getting which item is selected, you basically need to iterate through the items in the group calling isSelected.

like image 22
Mark Elliot Avatar answered Oct 02 '22 06:10

Mark Elliot