Java Reference
In-Depth Information
The following program builds up a small but typical menu and traps the action events
from the menu items. To keep the program readable, it is a good idea to use a separate
method for each menu or set of related menus. Have a look at the
createFaceItem
method, which creates a menu item to change the font face. The
same listener class takes care of three cases, with the
name
parameters varying for
each menu item. The same strategy is used for the
createSizeItem
and
createStyleItem
methods.
ch18/menu/FontViewer2.java
1
import
javax.swing.JFrame;
2
3 /**
4
This program uses a menu to display font
effects.
5 */
6
public class
FontViewer2
7 {
8
public static void
main(String[] args)
9 {
10 JFrame frame =
new
FontViewer2Frame();
11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_
12 frame.setVisible(
true
);
13 }
14 }
803
804
ch18/menu/FontViewer2Frame.java
1
import
java.awt.BorderLayout;
2
import
java.awt.Font;
3
import
java.awt.GridLayout;
4
import
java.awt.event.ActionEvent;
5
import
java.awt.event.ActionListener;
6
import
javax.swing.ButtonGroup;
7
import
javax.swing.JButton;
8
import
javax.swing.JCheckBox;
9
import
javax.swing.JComboBox;
10
import
javax.swing.JFrame;
11
import
javax.swing.JLabel;
12
import
javax.swing.JMenu;