Skip to main content

The ButtonGroup of my dreams

Posted by alexfromsun on August 23, 2006 at 10:34 AM PDT

I have fixed quite a lot of bugs and RFE's in Swing for Java 1.6 and don't really remember all of them,
but I do remember one remarkable bug because it took me unusually long time to find a good solution

and after I had fixed it I had to fix several regressions and finally
I completely rolled the fix back

Let me introduce you the bug number 4226243
(and 10 related bugs)

So why fixing it was so difficult ?

We just should be able to move the focus and selection inside the RadioButtonGroup with help of arrow keys...

That doesn't look like a hard problem

But we also need to skip unselected radioButtons if we move focus from component to component pressing "Tab" button,
just like Windows or GTK do it.

Test any native application with RadioButtonGroup and you will see that

if a RadioButtonGroup has a selected button it is impossible to focus unselected one with help of "Tab" of "Shift+Tab" buttons.

Native ButtonGroup behaviours like a one component:

you press "Tab" -> focus gets the selected button

press "Tab" again -> focus goes out

selection can be changed with help of arrow keys (or by clicking mouse)

This part turned out to be really problematic...

The real killer was the fact that javax.swing.ButtonGroup is not a Swing component,
it implements a set of buttons which can be placed on differect panels and
theoretically speaking even on different frames !


it might explain why our focus management wasn't ready to such an unnatural request

Finally with great help of AWT team we found a workable fix

but since it is supposed to use some reflection and other hacks

I doubt we will accept this version

It probably was a sad story, but the time wasn't spent in vain

as a result of lengthy work on that bug I got a clear vision of

Better ButtonGroup implementation

Please welcome JXButtonGroupPanel from SwingHelper project

  1. It transparently adds all its children buttons
    to the group
  2. Can be used as for exclusive JRadioButtons group as well as for group of JButtons
  3. Supports arrow keys and correctly works with focus for exclusive groups
  4. Just makes it easier to implement typical button groups

You just add your buttons to JXButtonGroupPanel and it will do the rest of the work

Please try it and share you opinion !

Note: Please read the Follow up blog

Related Topics >>