Java Swing: Menus and Toolbars, Part 6
O'Reilly Book Excerpts: Java Swing, 2nd Edition

Java Swing: Menus and Toolbars, Part 6

by Robert Eckstein, Marc Loy, Dave Wood, James Elliott, Brian Cole

In part six in this book excerpt series on Swing menus and toolbars from Java Swing, 2nd Edition, learn how to use complex menu items like radio buttons and checkbox menus.

Selectable Menu Items

So far, we've covered traditional menu items that produce a simple, text-oriented label associated with an action. But that's not the only type of item to which users are accustomed. Swing provides for two selectable menu items: the checkbox menu item and the radio button menu item.

The JCheckBoxMenuItem Class

Checkbox menu items are represented by the JCheckBoxMenuItem class. As you might have guessed, this object behaves similarly to the JCheckBox object. By clicking on a checkbox menu item, you can toggle a UI-defined checkmark that generally appears to the left of the menu item's label. There is no mutual exclusion between adjoining JCheckBoxMenuItem objects-- the user can check any item without affecting the state of the others. Figure 14-14 shows the class diagram for the JCheckBoxMenuItem component.

Figure 14-14. JCheckBoxMenuItem class diagram

Properties

Table 14-9 shows the properties of the JCheckBoxMenuItem class. JCheckBoxMenuItem inherits the JMenuItem model (ButtonModel) and its accessors. The JCheckBoxMenuItem class also contains two additional component properties. The state property has the value true if the menu item is currently in the checked state, and false if it is not. The selectedObjects property contains an Object array of size one, consisting of the text of the menu item if it is currently in the checked state. If it is not, getSelectedObjects( ) returns null. The getSelectedObjects( ) method exists for compatibility with AWT's ItemSelectable interface.

Table 14-9: JCheckBoxMenuItem properties

Property

Data type

get

is

set

Default value

accessibleContexto

AccessibleContext

·

 

 

JCheckBoxMenuItem.
  AccessibleJCheckBoxMenuItem( )

selectedObjectso

Object[ ]

·

 

 

 

state

boolean

·

 

·

false

UIb

CheckBoxMenuItemUI

·

 

·

From L&F

UIClassIDo

String

·

 

 

"CheckBoxMenuItem"

bbound, ooverridden
See also properties from the JMenuItem class (Table 14-4).


Constructors

public JCheckBoxMenuItem(  )

public JCheckBoxMenuItem(Action action)

public JCheckBoxMenuItem(Icon icon)

public JCheckBoxMenuItem(String text) 

public JCheckBoxMenuItem(String text, Icon icon)

public JCheckBoxMenuItem(String text, boolean checked)

public JCheckBoxMenuItem(String text, Icon icon, boolean checked)

These constructors initialize the JCheckBoxMenuItem with a specified action (since Version 1.3), icon, or string. The additional boolean value initializes the state property, specifying whether the menu item is initially checked.

Miscellaneous

public void updateUI(  )

Force the current UI manager to reset and repaint the delegate for the component, thus updating the component's L&F.

Using Checkbox Menu Items

Here's a program using the JCheckBoxMenuItem class. It is similar to the JMenu example, except that each menu item now has a checkmark next to it. We've done nothing to make the items mutually exclusive; that comes next. We have, however, reworked the code to use more-portable keyboard accelerators rather than mnemonics. Note that we used M (middle) as the accelerator for the Center option because C is generally reserved for Copy. Figure 14-15 shows the result.

// CheckBoxMenuItemExample.java

//

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.border.*;



public class CheckBoxMenuItemExample extends JPanel {

    public JTextPane pane;

    public JMenuBar menuBar;

    public JToolBar toolBar;



    public CheckBoxMenuItemExample(  ) {

        menuBar = new JMenuBar(  );

        JMenu justifyMenu = new JMenu("Justify");

        ActionListener actionPrinter = new ActionListener(  ) {

            public void actionPerformed(ActionEvent e) {

                try { pane.getStyledDocument(  ).insertString(0 ,

                      "Action ["+e.getActionCommand(  )+"] 

					     performed!\n", null);

                } catch (Exception ex) { ex.printStackTrace(  ); }

            }

        };

        JCheckBoxMenuItem leftJustify = new

               JCheckBoxMenuItem("Left", new ImageIcon("left.gif"));

        leftJustify.setHorizontalTextPosition(JMenuItem.RIGHT);

        leftJustify.setAccelerator(KeyStroke.getKeyStroke('L',

                        Toolkit.getDefaultToolkit(  ).getMenuShortcutKeyMask(  )));

        leftJustify.addActionListener(actionPrinter);

        JCheckBoxMenuItem rightJustify = new

               JCheckBoxMenuItem("Right", new ImageIcon("right.gif"));

        rightJustify.setHorizontalTextPosition(JMenuItem.RIGHT);

        rightJustify.setAccelerator(KeyStroke.getKeyStroke('R',

                        Toolkit.getDefaultToolkit(  ).getMenuShortcutKeyMask(  )));

        rightJustify.addActionListener(actionPrinter);

        JCheckBoxMenuItem centerJustify = new

               JCheckBoxMenuItem("Center", new ImageIcon("center.gif"));

        centerJustify.setHorizontalTextPosition(JMenuItem.RIGHT);

        centerJustify.setAccelerator(KeyStroke.getKeyStroke('M',

                        Toolkit.getDefaultToolkit(  ).getMenuShortcutKeyMask(  )));

        centerJustify.addActionListener(actionPrinter);

        JCheckBoxMenuItem fullJustify = new

               JCheckBoxMenuItem("Full", new ImageIcon("full.gif"));

        fullJustify.setHorizontalTextPosition(JMenuItem.RIGHT);

        fullJustify.setAccelerator(KeyStroke.getKeyStroke('F',

                        Toolkit.getDefaultToolkit(  ).getMenuShortcutKeyMask(  )));

        fullJustify.addActionListener(actionPrinter);



        justifyMenu.add(leftJustify);

        justifyMenu.add(rightJustify);

        justifyMenu.add(centerJustify);

        justifyMenu.add(fullJustify);



        menuBar.add(justifyMenu);

        menuBar.setBorder(new BevelBorder(BevelBorder.RAISED));



    }

    public static void main(String s[ ]) {

        CheckBoxMenuItemExample example = new CheckBoxMenuItemExample(  );

        example.pane = new JTextPane(  );

        example.pane.setPreferredSize(new Dimension(250, 250));

        example.pane.setBorder(new BevelBorder(BevelBorder.LOWERED));



        JFrame frame = new JFrame("Menu Example");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setJMenuBar(example.menuBar);

        frame.getContentPane(  ).add(example.pane, BorderLayout.CENTER);

        frame.pack(  );

        frame.setVisible(true);

    }

}

Figure 14-15. A series of checkbox menu items

The JRadioButtonMenuItem Class

Swing implements radio button menu items with the JRadioButtonMenuItem class. As you might expect, it shares the characteristics of the JRadioButton class and is intended to represent a group of mutually exclusive choices. Some L&Fs indicate this exclusivity visually by showing circular "buttons" to the left of the selectable choices.

TIP: Even though L&Fs visually distinguish between checkbox and radio button items, the distinction can be subtle and unfamiliar to users, so it's a good idea to use separators (see "The JSeparator Class" later in this chapter) as well as other visual cues that suggest the logical grouping of mutually exclusive items within the menu.

Although you might expect otherwise, radio button menu items don't enforce mutual exclusion by themselves. Instead, you need to use a ButtonGroup object to limit the user to a single selection. Figure 14-16 shows the class diagram for the JRadioButtonMenuItem component.

Figure 14-16. Radio button menu item class diagram

Properties

Table 14-10 shows the properties of the JRadioButtonMenuItem class. Unlike JCheckBoxMenuItem, there is no state property that indicates the current selection state of the menu item. Instead, you typically use this class in conjunction with a ButtonGroup, which contains a getSelected( ) method for extracting the correct object.

Table 14-10: JRadioButtonMenuItem properties

Property

Data type

get

is

set

Default value

accessibleContexto

AccessibleContext

·

 

 

JRadioButtonMenuItem.
  AccessibleJRadioButtonMenu-Item( )

UIb

RadioButtonMenuItemUI

·

 

·

From L&F

UIClassIDo

String

·

 

 

"RadioButtonMenuItem"

bbound, ooverridden
See also properties from the JMenuItem class (Table 14-4).


Constructor

public JRadioButtonMenuItem(  )

public JRadioButtonMenuItem(Action action)

public JRadioButtonMenuItem(Icon icon)

public JRadioButtonMenuItem(String text)

public JRadioButtonMenuItem(String text, Icon icon)

Initialize the JRadioButtonMenuItem with the specified action (since Version 1.3), icon, or string.

Miscellaneous

public void updateUI(  )

Force the current UI manager to reset and repaint the delegate for the component, thus updating the component's L&F.

[1] [2] Next

Close    To Top
  • Prev Article-Java:
  • Next Article-Java:
  • Now: Tutorial for Web and Software Design > Java > Java Basic > Java Content
    Photoshop Tutorial
     

    Special Effect

      3D Effect
      Photoshop Articles
    Programming Tutorial
     

    C/C++ Tutorial

      Visual Basic
      C# Tutorial
    Database Tutorial
     

    MySQL Tutorial

      MS SQL Tutorial
      Oracle Tutorial
    Geek Tutorial
     

    Blogging Tutorial

      RSS Tutorial
      Podcasting Tutorial
    Graphic Design Tutorial
      Coreldraw Tutorial
      Illustrator Tutorial
      3D Tutorials
    Webmaster Articles
     

    Domain Service

      Web Hosting
      Site Promotion
    Java Tutorial/ Articles
     

    Java Servlets

      JavaEE Tutorial
     

    JavaBeans Tutorial

    XML Tutorial/ Articles
     

    XML Style

      AJAX Tutorial
      XML Mobile
    Flash Tutorial/ Articles
     

    Flash Video

      Action Script
      Flash Articles
    OS Tutorial/ Articles
      Linux Tutorial
      Symbian Tutorial
      MacOS Tutorial
    Personal Tech
      Hardware Tutorial
      Software Tutorial
      Online Auction