Simple Example.java

This example when run, creates a top level window with a menubar and two radio button groups. The menubar has two choices, and each radio button group has three choices. The example highlights how to use the following Swing classes:

And the following methods:

First the code creates a JPanel, which is a generic lightweight container (something to place other components inside of) and a JLabel. We attach the JLabel to JPanel using the "setLabelFor()" method. We also "setDisplayedMnemonic('P')" for the JLabel and place the JLabel inside the JPanel using the "add" method.

JPanel holdBut1 = new JPanel();
JLabel label1 = new JLabel ("Pluggable L&F Radio Button Panel ");
label1.setDisplayedMnemonic('P');
label1.setLabelFor(holdBut1);
holdBut1.add(label1);

Next, we create some radio buttons, and then place the buttons in a Button Group. A ButtonGroup object means that only one of those buttons will be allowed to be "on" at a time. We also "setMnemonic('r')" for the Button Group, "add" the button(s) to the Button Group, and "add" the button(s) to the JPanel.

radio_but1 = new JRadioButton(red);
radio_but1.setMnemonic('r');

ButtonGroup group2 = new ButtonGroup();
group2.add(radio_but1);
holdBut2.add(radio_but1);

It is important from an accessibility and usability standoint, to use the "setLabelFor()" method to attach the JLabel to the JPanel, and to place the Button Group in the same JPanel. Visuallly, the JLabel "looks" attached to the JPanel by its location, but using the setLabelFor() attaches the JLabel to the JPanel such that assistive technologies can "locate" the JLabel associated with the JPanel programmatically. Also, the Button Group must be placed in a JPanel to allow the JLabel to be attached, since you cannot attach a JLabel to a Button Group.

Finally, this example show how easy it is to create hot keys or "mnemonics" for the menubar and menu items and short cut keys or "keyAccelerators" for the menu items. Again, from an accessibility and usability standoint, it is important to provide keyboard access to all the components in the application. Below is an example of how to use the "setMnemonic()" and "setAccelerator()" methods.

JMenuItem firstItemA = new JMenuItem("New ");
firstItemA.setMnemonic('N');

firstItemA.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK, false));