I've added a JToggleButton to a ButtonGroup.

Then I can't unselect this ToggleButton by clicking it one more time anymore.

I'm pretty sure that JToggleButton can be unselected by clicking it.

Is there any simple way to let the Button works as normal?

The Basic ButtonGroup works fine(Click B and unselect A).

But what i want is when A is selected and can be unselected by clicking it one more time.

In short,I want Both situations work.

A selected--> click B --> A unselected

A selected--> click A --> A unselected (Normal JToggleButton)

enter image description here

有帮助吗?

解决方案

In short yes... without a ButtonGroup everything works as expected, however:

You should generally initialize a group of radio buttons so that one is selected. However, the API doesn't enforce this rule — a group of radio buttons can have no initial selection. Once the user has made a selection, exactly one button is selected from then on.

So basically the only time no JToggle button can be selected is at start up. The minute one is selected we can only change the selected, we cannot unselect everything. And if we think about it logically it makes sense, imagine we have 2 options yes or no... atleast one option must have been selected/enforced at the time. Or you must add more alternatives like yes, no and still thinking (dumb example but im not good at explaining).

but there is always a work around:

There's no supported API for un-selecting all the buttons. However, if you really want to un-select all the buttons (not that it's recommended), calling setSelected(null, true) on the ButtonGroup should do the trick.

Reference:

其他提示

You might on the unselection event of both buttons do a ButtonGroup.clearSelection() but then, you could leave out the ButtonGroup (misuse?) and simple listen to the selection state.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top