tags:

views:

51

answers:

2

In a set of radio buttons of the same group, only one can be selected at the same time. I would like to have the same behaviour with a normal button.

Imagine there's a row of 3 buttons. When a button is selected it changes: but.setSelected(true) and the other two buttons should be NOT selected: but.setSelected(false)

Now, is there a generic, simple and clean solution to accomplish that in Java (Swing) ?

+3  A: 

JButton extends AbstractButton (in the same way JRadioButton does) and hence you can use the same solution as with JRadioButton: Simply add a number of JButtons to a ButtonGroup.

However, typically this approach will be unintuitive to the end user as people don't generally expect buttons to remain "stuck down"; This is specifically why JRadioButtons exist.

Adamski
Your right using this with standard JButton will make the users lost, but you can want this behaviour with JToggleButton.
Matthieu BROUILLARD
It's a good point - You should use JToggleButton to ensure that the button remains stuck down. JRadioButton and JCheckBox are both subclasses of JToggleButton.
Adamski
+1  A: 

The is a special component for that - JToggleButton. It is exactly what you want. It can be used with ButtonGroup as radio buttons and check boxes (they are descendants of toggle button)

eugener
+1 In addition, putting `JToggleButton`s in a `ButtonGroup` will produce the required single-selection. http://java.sun.com/javase/6/docs/api/javax/swing/ButtonGroup.html
trashgod