How do I relate more then one radio button (JRadioButton) to a button group using VAJ's Visual Composition Editor?

Eric Rizzo

[Note: JToggleButton or any subclass, including JRadioButton and JCheckBox, will work correctly with a ButtonGroup]

There are a couple of different ways to use the Swing ButtonGroup in the VCE, a long (tedious) way and a short (simpler) way. The long way uses only what is available in basic Swing and the VCE, while the shortcut uses a custom class to make things easier. I'll describe both.

The traditional (long) method

  1. Place your JRadioButton, JToggleButton, and/or JCheckBox instances on your component as normal.
  2. Use the "Choose Bean" icon to place an instance of ButtonGroup on your VCE free-form area (the blank space outside your visual components).
  3. For each button you want included in the ButtonGroup, repeat the following:
    • Connect from the main component's initialize() event [right-click in the empty free-form area, choose Connect > Connectable features... > initialize()] and choose the the add() method of the ButtonGroup as the destination.
    • Connect the "this" property of the radio/toggle/checkbox button to the "b" property of the connection in the above step.
As you can see, this can get tedious and lead to a tangle of connections if you have more than a couple of radio/toggle/checkbox buttons. However, it works "out of the box" with VAJ and generates straightforward (if not efficient) Swing code.

The shortcut method

Because this is so tedious and spaghetti-like, I wrote a component named ButtonGroupPanel that was designed just for the purpose of making ButtonGroup easy to use in the VCE. It is a subclass of JPanel that has an encapsulated ButtonGroup to which all buttons get added when they are added to the panel.
At http://www.rizzoweb.com/Java/ButtonGroupPanel/ you will find a ZIP file with my ButtonGroupPanel class in a JAR, also the JavaDoc for the class and a VAJ repository that you can import into your VisualAge. It has a sample test program that demonstrates how to use the ButtonGroupPanel in the Visual Editor. If you import the .dat file into your VAJ, you can then add the package erizzo.swing to your workspace and open up the class ButtonGroupPanelTester in the VCE to see how it is used.
I think you'll find this panel makes ButtonGroups a lot easier to work with in the Visual Composition Editor, if you can live with using a third-party component. If you don't want to rely on my ButtonGroupPanel, write a similar thing yourself - it's not very difficult if you understand how Swing and JPanel work.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.