Skip to main content

KISS principle: JXButtonGroupPanel followup

Posted by alexfromsun on November 1, 2006 at 1:28 PM EST

In one of my previous blog I presented a component which enables arrow keys to transfer focus and selection for Swing buttons.
And it worked very well, but there were two things which worried me

  • JXButtonGroupPanel offered a different way to bind buttons to a ButtonGroup
    since it created ButtonGroup and filled it up behind the scene
  • It was just overcomplicated

That why I mentioned Keep It Simple principle
Actually I like to control what is going on in my applications and don't like when componets are trying to be too smart.
Indeed, when you need to add some JRadioButtons to a panel, you usually do something like this:

JPanel panel = new JPanel(); 
// Create a ButtonGroup         
ButtonGroup group = new ButtonGroup(); 
 
JRadioButton r1 = new JRadioButton("One"); 
// Add a button to the panel    
panel.add(r1); 
// Add a button to the ButtonGroup 
group.add(r1); 
 
JRadioButton r2 = new JRadioButton("Two"); 
panel.add(r2); 
group.add(r2); 
JRadioButton r3 = new JRadioButton("Three"); 
panel.add(r3); 
group.add(r3); 
 
frame.add(panel);

I would prefer to change the existing code as little as possible if I just want to enable arrow keys support.

With all mentioned reasons in mind I rewrote JXButtonGroupPanel to make it shorter and easier to use
I even cut down its name from JXButtonGroupPanel to JXButtonPanel :-)

On the SwingHelper project you can as usual find the buttongroup.jar and buttonpanel-src.zip

Direct link to JXButtonPanel sources

The demo is also rewritten to take advantage of the new implementation

Summary

  • Just change your JPanel to JXButtonPanel and arrow keys will work
  • It doesn't fill a ButtonGroup up behind the scene anymore
  • Based on a comment from paulo_matos I added a groupSelectionFollowFocus property
    which controls whether arrow keys should transfer button's selection as well as focus or not
  • It is fully tested and ready for production

Your comments are welcome !
Thanks
alexp

Related Topics >>