JMenu Example
A problem for interface designers is how to manage the 'real estate', how to make best use of available screen space. Menus, with their limited use of space, are an efficient way of allowing users to navigate 'busy' user interfaces.
In this example JMenu instances are added to a JMenuBar to construct a menu.
JMenuItem instances are added to each JMenu.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// JMenu Example
import java.awt.*;
import javax.swing.*;
class JMenuExample {
public static void main(String[] args) {
JMenu menu1 = new JMenu("File");
menu1.add(new JMenuItem("New"));
menu1.add(new JMenuItem("Open"));
menu1.add(new JSeparator());
menu1.add(new JMenuItem("Save"));
menu1.add(new JMenuItem("Save as..."));
menu1.add(new JSeparator());
menu1.add(new JMenuItem("Exit"));
JMenu menu2 = new JMenu("Help");
menu2.add(new JMenuItem("Help Contents"));
menu2.add(new JSeparator());
menu2.add(new JMenuItem("About..."));
JMenuBar bar = new JMenuBar();
bar.add(menu1);
bar.add(menu2);
JFrame frame = new JFrame();
frame.setJMenuBar(bar);
frame.setSize(150,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
9-16 The first JMenu is constructed.
Note the use of a JSeparator to separate items.
Also notice the use of ellipsis (3 dots) as in the string "Save as...". This convention lets the user know that selecting the menu item will result in some further form of dialog taking place (although not in our example).
18-21 The second menu is constructed.
23-25 The menus are added to the menu bar.
28 The menu bar is attached to the frame.
