Java ScreenShot
Screenshot      

Screenshot Core Java 2: Volume I - Fundamentals

Table of Contents
 9.  User Interface Components with Swing


Menus

We started this chapter by introducing the most common components that you might want to place into a window, such as various kinds of buttons, text fields, and combo boxes. Swing also supports another type of user interface elements, the pull-down menus that are familiar from GUI apps. A menu bar on top of the window contains the names of the pull-down menus. Clicking on a name opens the menu containing menu items and submenus. When the user clicks on a menu item, all menus are closed and a message is sent to the program. Screenshot-22 shows a typical menu with a submenu.

Screenshot-22. A menu with a submenu

Java graphics 09fig22.gif


Building Menus

Building menus is straightforward. You create a menu bar:

JMenuBar menuBar = new JMenuBar();


A menu bar is just a component that you can add anywhere you like. Normally, you want it to appear at the top of a frame. You can add it there with the setJMenuBar method:

frame.setJMenuBar(menuBar);


For each menu, you create a menu object:

JMenu editMenu = new JMenu("Edit");


You add the top-level menus to the menu bar:

menuBar.add(editMenu);


You add menu items, separators, and submenus to the menu object:

JMenuItem pasteItem = new JMenuItem("Paste");
editMenu.add(pasteItem);
editMenu.addSeparator();
JMenu optionsMenu = . . .; // a submenu editMenu.add(optionsMenu);


When the user selects a menu, an action event is triggered. You need to install an action listener for each menu item.

ActionListener listener = . . .;
pasteItem.addActionListener(listener);


There is a convenient method JMenu.add(String s) that adds a menu item to the end of a menu, for example:

editMenu.add("Paste");


The add method returns the created menu item, so that you can capture it and then add the listener, as follows:

JMenuItem pasteItem = editMenu.add("Paste");
pasteItem.addActionListener(listener);


It often happens that menu items trigger commands that can also be activated through other user interface elements such as toolbar buttons. In , you saw how to specify commands through Action objects. You define a class that implements the Action interface, usually by extending the AbstractAction convenience class. You specify the menu item label in the constructor of the AbstractAction object, and you override the actionPerformed method to hold the menu action handler. For example,

Action exitAction = new
 AbstractAction("Exit") // menu item text goes here
 {
 public void actionPerformed(ActionEvent event)
 {
 // action code goes here
 System.exit(0);
 }
 };


You can then add the action to the menu:

JMenuItem exitItem = fileMenu.add(exitAction);


This command adds a menu item to the menu, using the action name. The action object becomes its listener. This is just a convenient shortcut for

JMenuItem exitItem = new JMenuItem(exitAction);
fileMenu.add(exitItem);


Java graphics notes_icon.gif

In Windows and Macintosh programs, menus are generally defined in an external resource file and tied to the app with resource identifiers. It is possible to build menus programmatically, but it is not commonly done. In Java, menus are still usually built inside the program because the mechanism for dealing with external resources is far more limited than it is in Windows or Mac OS.

javax.swing.JMenu 1.2

Java graphics api_icon.gif
  • JMenu(String label)

    Parameters:

    label

    The label for the menu in the menu bar or parent menu

  • JMenuItem add(JMenuItem item)

    adds a menu item (or a menu).

    Parameters:

    item

    The item or menu to add

  • JMenuItem add(String label)

    adds a menu item to this menu.

    Parameters:

    label

    The label for the menu items

  • JMenuItem add(Action a)

    adds a menu item and associates an action with it.

    Parameters:

    a

    An action encapsulating a name, optional icon, and listener (see )

  • void addSeparator()

    adds a separator line to the menu.

  • JMenuItem insert(JMenuItem menu, int index)

    adds a new menu item (or submenu) to the menu at a specific index.

    Parameters:

    menu

    The menu to be added

     

    index

    Where to add the item

  • JMenuItem insert(Action a, int index)

    adds a new menu item at a specific index and associates an action with it.

    Parameters:

    a

    An action encapsulating a name, optional icon, and listener

     

    index

    Where to add the item

  • void insertSeparator(int index)

    adds a separator to the menu.

    Parameters:

    index

    Where to add the separator

  • void remove(int index)

    removes a specific item from the menu.

    Parameters:

    index

    The position of the item to remove

  • void remove(JMenuItem item)

    removes a specific item from the menu.

    Parameters:

    item

    The item to remove

javax.swing.JMenuItem 1.2

Java graphics api_icon.gif
  • JMenuItem(String label)

    Parameters:

    label

    The label for this menu item

  • JMenuItem(Action a) 1.3

    Parameters:

    a

    An action encapsulating a name, optional icon, and listener

javax.swing.AbstractButton 1.2

Java graphics api_icon.gif
  • void setAction(Action a) 1.3

    Parameters:

    a

    An action encapsulating a name, optional icon, and listener

javax.swing.JFrame 1.2

Java graphics api_icon.gif
  • void setJMenuBar(JMenuBar menubar)

    sets the menu bar for this frame.

Icons in Menu Items

Menu items are very similar to buttons. In fact, the JMenuItem class extends the AbstractButton class. Just like buttons, menus can have just a text label, just an icon, or both. You can specify the icon with the JMenuItem(String, Icon) or JMenuItem(Icon) constructor, or you can set it with the setIcon method that the JMenuItem class inherits from the AbstractButton class. Here is an example:

JMenuItem cutItem = new JMenuItem("Cut", new ImageIcon("cut.gif"));


Screenshot-23 shows a menu with icons next to several menu items. As you can see, by default, the menu item text is placed to the right of the icon. If you prefer the text to be placed on the left, call the setHorizontalTextPosition method that the JMenuItem class inherits from the AbstractButton class. For example, the call

cutItem.setHorizontalTextPosition(SwingConstants.LEFT);


Screenshot-23. Icons in menu items

Java graphics 09fig23.gif


moves the menu item text to the left of the icon. You can also add an icon to an action:

cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));


Whenever you construct a menu item out of an action, the Action.NAME value becomes the text of the menu item, and the Action.SMALL_ICON value becomes the icon. Alternatively, you can set the icon in the AbstractAction constructor:

cutAction = new
 AbstractAction("Cut", new ImageIcon("cut.gif"))
 {
 public void actionPerformed(ActionEvent event)
 {
 // action code goes here
 }
 };


javax.swing.JMenuItem 1.2

Java graphics api_icon.gif
  • JMenuItem(String label, Icon icon)

    Parameters:

    label

    The label for the menu item

     

    icon

    The icon for the menu item

javax.swing.AbstractButton 1.2

Java graphics api_icon.gif
  • void setHorizontalTextPosition(int pos)

    sets the horizontal position of the text relative to the icon.

    Parameters:

    pos

    SwingConstants.RIGHT (text is to the right of icon) or SwingConstants.LEFT

javax.swing.AbstractAction 1.2

Java graphics api_icon.gif
  • AbstractAction(String name, Icon smallIcon)

    Parameters:

    name

    the label for the action

     

    smallIcon

    the small icon for the action

Check Box and Radio Button Menu Items

Check box and radio button menu items display a check box or radio button next to the name (see Screenshot-24). When the user selects the menu item, the item automatically toggles between checked and unchecked.

Screenshot-24. A checked menu item and menu items with radio buttons

Java graphics 09fig24.gif


Apart from the button decoration, you treat these menu items just as you would any others. For example, here is how you create a check box menu item.

JCheckBoxMenuItem readonlyItem
 = new JCheckBoxMenuItem("Read-only");
optionsMenu.add(readonlyItem);


The radio button menu items work just like regular radio buttons. You must add them to a button group. When one of the buttons in a group is selected, all others are automatically deselected.

ButtonGroup group = new ButtonGroup();
JRadioButtonMenuItem insertItem
 = new JRadioButtonMenuItem("Insert");
insertItem.setSelected(true);
JRadioButtonMenuItem overtypeItem
 = new JRadioButtonMenuItem("Overtype");
group.add(insertItem);
group.add(overtypeItem);
optionsMenu.add(insertItem);
optionsMenu.add(overtypeItem);


With these menu items, you don't necessarily want to be notified at the exact moment the user selects the item. Instead, you can simply use the isSelected method to test the current state of the menu item. (Of course, that means that you should keep a reference to the menu item stored in an instance variable.) Use the setSelected method to set the state.

javax.swing.JCheckBoxMenuItem 1.2

Java graphics api_icon.gif
  • JCheckBoxMenuItem(String label)

    constructs the check box menu item with the given label.

  • JCheckBoxMenuItem(String label, boolean state)

    constructs the check box menu item with the given label and the given initial state (true is checked).

javax.swing.JRadioButtonMenuItem 1.2

Java graphics api_icon.gif
  • JRadioButtonMenuItem(String label)

    constructs the radio button menu item with the given label.

  • JRadioButtonMenuItem(String label, boolean state)

    constructs the radio button menu item with the given label and the given initial state (true is checked).

javax.swing.AbstractButton 1.2

Java graphics api_icon.gif
  • boolean isSelected()

    returns the check state of this item (true is checked).

  • void setSelected(boolean state)

    sets the check state of this item.

Pop-up Menus

A pop-up menu is a menu that is not attached to a menu bar but that floats somewhere (see Screenshot-25).

Screenshot-25. A pop-up menu

Java graphics 09fig25.gif


You create a pop-up menu similarly to the way you create a regular menu, but a pop-up menu has no title.

JPopupMenu popup = new JPopupMenu();


You then add menu items in the usual way:

JMenuItem item = new JMenuItem("Cut");
item.addActionListener(listener);
popup.add(item);


Unlike the regular menu bar that is always shown at the top of the frame, you must explicitly display a pop-up menu by using the show method. You specify the parent component and the location of the pop-up, using the coordinate system of the parent. For example:

popup.show(panel, x, y);


Usually you write code to pop up a menu when the user clicks a particular mouse button, the so-called pop-up trigger. In Windows, the pop-up trigger is the nonprimary (usually, the right) mouse button. To pop up a menu when the user clicks the pop-up trigger:

  1. Install a mouse listener.

  2. Add code like the following to the mouse listeners:

    public void mousePressed(MouseEvent event)
    {
     if (event.isPopupTrigger())
     popup.show(event.getComponent(),
     event.getX(), event.getY());
    }
    


This code will show the pop-up menu at the mouse location where the user clicked the pop-up trigger.

Java graphics caution_icon.gif

Some systems trigger popups when the mouse button goes down, others when the mouse button goes up. Therefore, you need to test for the popup trigger in both the mousePressed and the mouseReleased method.

javax.swing.JPopupMenu 1.2

Java graphics api_icon.gif
  • void show(Component c, int x, int y)

    shows the pop-up menu.

    Parameters:

    c

    The component over which the pop-up menu is to appear

     

    x, y

    The coordinates (in the coordinate space of c) of the top-left corner of the pop-up menu

  • boolean isPopupTrigger(MouseEvent event) 1.3

    returns true if the mouse event is the pop-up menu trigger.

javax.awt.event.MouseEvent 1.1

Java graphics api_icon.gif
  • boolean isPopupTrigger()

    returns true if this mouse event is the pop-up menu trigger.

Keyboard Mnemonics and Accelerators

It is a real convenience for the experienced user to select menu items by keyboard mnemonics. In Java, you can specify keyboard mnemonics for menu items by specifying a mnemonic letter in the menu item constructor:

JMenuItem cutItem = new JMenuItem("Cut", 'T');


The keyboard mnemonic is displayed automatically in the menu, by underlining the mnemonic letter (see Screenshot-26). For example, in the item defined in the last example, the label will be displayed as "Cut" with an underlined letter 't'. When the menu is displayed, the user just needs to press the T key, and the menu item is selected. (If the mnemonic letter is not part of the menu string, then typing it still selects the item, but the mnemonic is not displayed in the menu. Naturally, such invisible mnemonics are of dubious utility.)

Screenshot-26. Keyboard mnemonics

Java graphics 09fig26.gif


Sometimes, you don't want to underline the first letter of the menu item that matches the mnemonic. For example, if you have a mnemonic "A" for the menu item "Save As," then it makes more sense to underline the second "A" (Save As). As of SDK 1.4, you can specify which character you want to have underlined, by calling the setDisplayedMnemonicIndex method. If you have an Action object, you can add the mnemonic as the value of the Action.MNEMONIC_KEY key, as follows:

cutAction.putValue(Action.MNEMONIC_KEY, new Integer('T'));


You can only supply a mnemonic letter in the constructor of a menu item, not in the constructor for a menu. Instead, to attach a mnemonic to a menu, you need to call the setMnemonic method:

JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');


To select a top-level menu from the menu bar, you press the ALT key together with the mnemonic letter. For example, you press ALT+H to select the Help menu from the menu bar. Keyboard mnemonics let you select a submenu or menu item from the currently open menu. In contrast, accelerators are keyboard shortcuts that let you select menu items without ever opening a menu. For example, many programs attach the accelerators CTRL+O and CTRL+S to the Open and Save items in the File menu. You use the setAccelerator method to attach an accelerator key to a menu item. The setAccelerator method takes an object of type Keystroke. For example, the following call attaches the accelerator CTRL+O to the openItem menu item.

openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
 InputEvent.CTRL_MASK));


When the user presses the accelerator key combination, this automatically selects the menu option and fires an action event, as if the user had selected the menu option manually. You can attach accelerators only to menu items, not to menus. Accelerator keys don't actually open the menu. Instead, they directly fire the action event that is associated with a menu. Conceptually, adding an accelerator to a menu item is similar to the technique of adding an accelerator to a Swing component. (We discussed that technique in .) However, when the accelerator is added to a menu item, the key combination is automatically displayed in the menu (see Screenshot-27).

Screenshot-27. Accelerators

Java graphics 09fig27.gif


Java graphics caution_icon.gif

Action objects can have a keystroke value associated with the Action.ACCELERATOR_KEY key. However, the JMenuItem(Action) constructor ignores that keystroke.

Java graphics notes_icon.gif

Under Windows, ALT+F4 closes a window. But this is not an accelerator that was programmed in Java. It is a shortcut defined by the operating system. This key combination will always trigger the WindowClosing event for the active window regardless of whether there is a Close item on the menu.

javax.swing.JMenuItem 1.2

Java graphics api_icon.gif
  • JMenuItem(String label, int mnemonic).

    Parameters:

    label

    The label for this menu item

     

    mnemonic

    The mnemonic character for the item; this character will be underlined in the label

  • void setAccelerator(KeyStroke k)

    sets the keystroke k as accelerator for this menu item. The accelerator key is displayed next to the label.

javax.swing.AbstractButton 1.2

Java graphics api_icon.gif
  • void setMnemonic(char mnemonic)

    sets the mnemonic character for the button. This character will be underlined in the label.

    Parameters:

    mnemonic

    The mnemonic character for the button

  • void setDisplayedMnemonicIndex(int index) 1.4

    sets the index of the character to be underlined in the button text. Use this method if you don't want the first occurrence of the mnemonic character to be underlined.

    Parameters:

    index

    The index of the button text character to be underlined

Enabling and Disabling Menu Items

Occasionally, a particular menu item should be selected only in certain contexts. For example, when a document is opened for reading only, then the Save menu item is not meaningful. Of course, we could remove the item from the menu with the JMenu.remove method, but users would react with some surprise to menus whose contents keeps changing. Instead, it is better to deactivate the menu items that lead to temporarily inappropriate commands. A deactivated menu item is shown in gray, and it cannot be selected (see Screenshot-28).

Screenshot-28. Disabled menu items

Java graphics 09fig28.gif


To enable or disable a menu item, use the setEnabled method:

saveItem.setEnabled(false);


There are two strategies for enabling and disabling menu items. Each time circumstances change, you can call setEnabled on the relevant menu items or actions. For example, as soon as a document has been set to read-only mode, you can locate the Save and Save As menu items and disable them. Alternatively, you can disable items just before displaying the menu. To do this, you must register a listener for the "menu selected" event. The javax.swing.event package defines a MenuListener interface with three methods:

void menuSelected(MenuEvent evt)
void menuDeselected(MenuEvent evt)
void menuCanceled(MenuEvent evt)


The menuSelected method is called before the menu is displayed. It can therefore be used to disable or enable menu items. The following code shows how to disable the Save and Save As actions whenever the Read Only check box menu item is selected:

public void menuSelected(MenuEvent evt)
{
 saveAction.setEnabled(!readonlyItem.isSelected());
 saveAsAction.setEnabled(!readonlyItem.isSelected());
}


Java graphics caution_icon.gif

Disabling menu items just before displaying the menu is a clever idea, but it does not work for menu items that also have accelerator keys. Since the menu is never opened when the accelerator key is hit, the action is never disabled and the accelerator key still triggers it.

javax.swing.JMenuItem 1.2

Java graphics api_icon.gif
  • void setEnabled(boolean b)

    enables or disables the menu item.

javax.swing.event.Menulistener 1.2

Java graphics api_icon.gif
  • void menuSelected(MenuEvent e)

    is called when the menu has been selected, before it is opened.

  • void menuDeselected(MenuEvent e)

    is called when the menu has been deselected, after it has been closed.

  • void menuCanceled(MenuEvent e)

    is called when the menu has been canceled, for example, by clicking outside the menu.

Example 9-12 is a sample program that generates a set of menus. It shows all the features that you saw in this section: nested menus, disabled menu items, check box and radio button menu items, a pop-up menu, and keyboard mnemonics and accelerators.
Example 9-12 MenuTest.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import javax.swing.*;
 4. import javax.swing.event.*;
 5.
 6. public class MenuTest
 7. {
 8. public static void main(String[] args)
 9. {
 10. MenuFrame frame = new MenuFrame();
 11. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 12. frame.show();
 13. }
 14. }
 15.
 16. /**
 17. A frame with a sample menu bar.
 18. */
 19. class MenuFrame extends JFrame
 20. {
 21. public MenuFrame()
 22. {
 23. setTitle("MenuTest");
 24. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
 25.
 26. JMenu fileMenu = new JMenu("File");
 27. JMenuItem newItem = fileMenu.add(new TestAction("New"));
 28.
 29. // demonstrate accelerators
 30.
 31. JMenuItem openItem = fileMenu.add(new TestAction("Open"));
 32. openItem.setAccelerator(KeyStroke.getKeyStroke(
 33. KeyEvent.VK_O, InputEvent.CTRL_MASK));
 34.
 35. fileMenu.addSeparator();
 36.
 37. saveAction = new TestAction("Save");
 38. JMenuItem saveItem = fileMenu.add(saveAction);
 39. saveItem.setAccelerator(KeyStroke.getKeyStroke(
 40. KeyEvent.VK_S, InputEvent.CTRL_MASK));
 41.
 42. saveAsAction = new TestAction("Save As");
 43. JMenuItem saveAsItem = fileMenu.add(saveAsAction);
 44. fileMenu.addSeparator();
 45.
 46. fileMenu.add(new
 47. AbstractAction("Exit")
 48. {
 49. public void actionPerformed(ActionEvent event)
 50. {
 51. System.exit(0);
 52. }
 53. });
 54.
 55. // demonstrate check box and radio button menus
 56.
 57. readonlyItem = new JCheckBoxMenuItem("Read-only");
 58. readonlyItem.addActionListener(new
 59. ActionListener()
 60. {
 61. public void actionPerformed(ActionEvent event)
 62. {
 63. boolean saveOk = !readonlyItem.isSelected();
 64. saveAction.setEnabled(saveOk);
 65. saveAsAction.setEnabled(saveOk);
 66. }
 67. });
 68.
 69. ButtonGroup group = new ButtonGroup();
 70.
 71. JRadioButtonMenuItem insertItem
 72. = new JRadioButtonMenuItem("Insert");
 73. insertItem.setSelected(true);
 74. JRadioButtonMenuItem overtypeItem
 75. = new JRadioButtonMenuItem("Overtype");
 76.
 77. group.add(insertItem);
 78. group.add(overtypeItem);
 79.
 80. // demonstrate icons
 81.
 82. Action cutAction = new TestAction("Cut");
 83. cutAction.putValue(Action.SMALL_ICON,
 84. new ImageIcon("cut.gif"));
 85. Action copyAction = new TestAction("Copy");
 86. copyAction.putValue(Action.SMALL_ICON,
 87. new ImageIcon("copy.gif"));
 88. Action pasteAction = new TestAction("Paste");
 89. pasteAction.putValue(Action.SMALL_ICON,
 90. new ImageIcon("paste.gif"));
 91.
 92. JMenu editMenu = new JMenu("Edit");
 93. editMenu.add(cutAction);
 94. editMenu.add(copyAction);
 95. editMenu.add(pasteAction);
 96.
 97. // demonstrate nested menus
 98.
 99. JMenu optionMenu = new JMenu("Options");
100.
101. optionMenu.add(readonlyItem);
102. optionMenu.addSeparator();
103. optionMenu.add(insertItem);
104. optionMenu.add(overtypeItem);
105.
106. editMenu.addSeparator();
107. editMenu.add(optionMenu);
108.
109. // demonstrate mnemonics
110.
111. JMenu helpMenu = new JMenu("Help");
112. helpMenu.setMnemonic('H');
113.
114. JMenuItem indexItem = new JMenuItem("Index");
115. indexItem.setMnemonic('I');
116. helpMenu.add(indexItem);
117.
118. // you can also add the mnemonic key to an action
119. Action aboutAction = new TestAction("About");
120. aboutAction.putValue(Action.MNEMONIC_KEY,
121. new Integer('A'));
122. helpMenu.add(aboutAction);
123.
124. // add all top-level menus to menu bar
125.
126. JMenuBar menuBar = new JMenuBar();
127. setJMenuBar(menuBar);
128.
129. menuBar.add(fileMenu);
130. menuBar.add(editMenu);
131. menuBar.add(helpMenu);
132.
133. // demonstrate pop-ups
134.
135. popup = new JPopupMenu();
136. popup.add(cutAction);
137. popup.add(copyAction);
138. popup.add(pasteAction);
139.
140. getContentPane().addMouseListener(new
141. MouseAdapter()
142. {
143. public void mousePressed(MouseEvent event)
144. {
145. if (event.isPopupTrigger())
146. popup.show(event.getComponent(),
147. event.getX(), event.getY());
148. }
149.
150. public void mouseReleased(MouseEvent event)
151. {
152. if (event.isPopupTrigger())
153. popup.show(event.getComponent(),
154. event.getX(), event.getY());
155. }
156. });
157. }
158.
159. public static final int DEFAULT_WIDTH = 300;
160. public static final int DEFAULT_HEIGHT = 200;
161.
162. private Action saveAction;
163. private Action saveAsAction;
164. private JCheckBoxMenuItem readonlyItem;
165. private JPopupMenu popup;
166. }
167.
168. /**
169. A sample action that prints the action name to System.out
170. */
171. class TestAction extends AbstractAction
172. {
173. public TestAction(String name) { super(name); }
174.
175. public void actionPerformed(ActionEvent event)
176. {
177. System.out.println(getValue(Action.NAME)
178. + " selected.");
179. }
180. }


Tool Bars

A tool bar is a button bar that gives quick access to the most commonly used commands in a program (see Screenshot-29).

Screenshot-29. A tool bar

Java graphics 09fig29.gif


What makes tool bars special is that you can move them elsewhere. You can drag the tool bar to one of the four borders of the frame (see Screenshot-30). When you release the mouse button, the tool bar is dropped into the new location (see Screenshot-31).

Screenshot-30. Dragging the tool bar

Java graphics 09fig30.gif


Screenshot-31. Dragging the tool bar to another border

Java graphics 09fig31.gif


Java graphics notes_icon.gif

Tool bar dragging works if the tool bar is inside a container with a border layout, or any other layout manager that supports the North, East, South, and West constraints.

The tool bar can even be completely detached from the frame. A detached tool bar is contained in its own frame (see Screenshot-32). When you close the frame containing a detached tool bar, the tool bar jumps back into the original frame.
Screenshot-32. Detaching the tool bar

Java graphics 09fig32.gif


Tool bars are straightforward to program. You add components into the tool bar:

JToolBar bar = new JToolBar();
bar.add(blueButton);


The JToolBar class also has a method to add an Action object. Simply populate the tool bar with Action objects, like this:

bar.add(blueAction);


The small icon of the action is displayed in the tool bar.

Java graphics caution_icon.gif

In SDK version 1.2, the name of the action shows up on the tool bar, which makes the button far too large. Therefore, you cannot share an Action object between a menu and a toolbar in SDK version 1.2. This problem has been fixed in version 1.3.

You can separate groups of buttons with a separator:
bar.addSeparator();


For example, the tool bar in Screenshot-29 has a separator between the third and fourth button. Then, you add the tool bar to the container.

contentPane.add(bar, BorderLayout.NORTH);


You can also specify a title for the toolbar that appears when the toolbar is undocked:

bar = new JToolBar(titleString);


By default, toolbars are initially horizontal. To have a toolbar start out as vertical, use

bar = new JToolBar(SwingConstants.VERTICAL)


or

bar = new JToolBar(titleString, SwingConstants.VERTICAL)


Buttons are the most common components inside toolbars. But there is no restriction on the components that you can add to a tool bar. For example, you can add a combo box to a tool bar.

Java graphics exclamatory_icon.gif

You can find nice tool bar buttons at http://developer.java.oracle.com/developer/techDocs/hi/repository.

Tool Tips

A disadvantage of tool bars is that users are often mystified by the meanings of the tiny icons in tool bars. To solve this problem, tool tips were invented. A tool tip is activated when the cursor rests for a moment over a button. The tool tip text is displayed inside a colored rectangle. When the user moves the mouse away, the tool tip is removed.

Screenshot-33. A tool tip

Java graphics 09fig33.gif


In Swing, you can add tool tips to any JComponent simply by calling the setToolTipText method:

exitButton.setToolTipText("Exit");


Alternatively, if you use Action objects, you associate the tool tip with the SHORT_DESCRIPTION key:

exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");


Example 9-13 is a program that shows how the same Action objects can be added to a menu and a tool bar. Note that the action names show up as the menu item names in the menu, and as the tool tips in the tool bar.

Example 9-13 ToolBarTest.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import java.beans.*;
 4. import javax.swing.*;
 5.
 6. public class ToolBarTest
 7. {
 8. public static void main(String[] args)
 9. {
10. ToolBarFrame frame = new ToolBarFrame();
11. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12. frame.show();
13. }
14. }
15.
16. /**
17. A frame with a toolbar and menu for color changes.
18. */
19. class ToolBarFrame extends JFrame
20. {
21. public ToolBarFrame()
22. {
23. setTitle("ToolBarTest");
24. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
25.
26. // add a panel for color change
27.
28. Container contentPane = getContentPane();
29. panel = new JPanel();
30. contentPane.add(panel, BorderLayout.CENTER);
31.
32. // set up actions
33.
34. Action blueAction = new ColorAction("Blue",
35. new ImageIcon("blue-ball.gif"), Color.BLUE);
36. Action yellowAction = new ColorAction("Yellow",
37. new ImageIcon("yellow-ball.gif"), Color.YELLOW);
38. Action redAction = new ColorAction("Red",
39. new ImageIcon("red-ball.gif"), Color.RED);
40.
41. Action exitAction = new
42. AbstractAction("Exit", new ImageIcon("exit.gif"))
43. {
44. public void actionPerformed(ActionEvent event)
45. {
46. System.exit(0);
47. }
48. };
49. exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");
50.
51. // populate tool bar
52.
53. JToolBar bar = new JToolBar();
54. bar.add(blueAction);
55. bar.add(yellowAction);
56. bar.add(redAction);
57. bar.addSeparator();
58. bar.add(exitAction);
59. contentPane.add(bar, BorderLayout.NORTH);
60.
61. // populate menu
62.
63. JMenu menu = new JMenu("Color");
64. menu.add(yellowAction);
65. menu.add(blueAction);
66. menu.add(redAction);
67. menu.add(exitAction);
68. JMenuBar menuBar = new JMenuBar();
69. menuBar.add(menu);
70. setJMenuBar(menuBar);
71. }
72.
73. public static final int DEFAULT_WIDTH = 300;
74. public static final int DEFAULT_HEIGHT = 200;
75.
76. private JPanel panel;
77.
78. /**
79. The color action sets the background of the frame to a
80. given color.
81. */
82. class ColorAction extends AbstractAction
83. {
84. public ColorAction(String name, Icon icon, Color c)
85. {
86. putValue(Action.NAME, name);
87. putValue(Action.SMALL_ICON, icon);
88. putValue(Action.SHORT_DESCRIPTION,
89. name + " background");
90. putValue("Color", c);
91. }
92.
93. public void actionPerformed(ActionEvent evt)
94. {
95. Color c = (Color)getValue("Color");
96. panel.setBackground(c);
97. }
98. }
99. }


javax.swing.JToolBar 1.2

Java graphics api_icon.gif
  • JToolBar()
  • JToolBar(String titleString)
  • JToolBar(int orientation)
  • JToolBar(String titleString, int orientation)

    construct a tool bar with the given title string and orientation. orientation is one of SwingConstants.HORIZONTAL (the default) and SwingConstants.VERTICAL.

  • JButton add(Action a)

    constructs a new button inside the tool bar with name, icon, and action callback from the given action, and adds the button to the end of the tool bar.

  • void addSeparator()

    adds a separator to the end of the tool bar.

javax.swing.JComponent 1.2

Java graphics api_icon.gif
  • void setToolTipText(String text)

    sets the text that should be displayed as a tool tip when the mouse hovers over the component.


Java ScreenShot
Screenshot      
Top
 

Comments