Java Reference
In-Depth Information
The AWT classes MenuBar, Menu, and MenuItem are used to create a menu
for a Frame. The Swing classes JMenuBar, JMenu, and JMenuItem are used to
create a menu for a JFrame. The process is similar for both AWT and Swing, so
I will only discuss how it works for Swing.
To add a menu to a JFrame, you perform the following steps:
1.
Instatiate a new JMenuBar object, and attach it to the JFrame using the
setJMenuBar() method of the JFrame class.
2.
Instantiate one or more JMenu objects, and add them to the JMenuBar
using the add(JMenu menu) method of the JMenuBar class.
3.
Instantiate one or more JMenuItem objects, and add them to a JMenu
object using the add(JMenuItem) method of the JMenu class.
4.
Add an ActionListener to each menu item to handle the ActionEvent
that is generated when a user selects the menu item.
To demonstrate menus, the following MenuDemo program adds a menu to
a JFrame. (The MenuColorChanger class that handles the events is available
on the Web site for this topic.) Study the createMenu() method and try to deter-
mine how the menu will look. (I sneaked in a cascading menu and a check box
menu item just to demonstrate their use, as shown in the output in Figure
13.14.) Notice that the event handling for the buttons and menu items is iden-
tical, which is possible because they both generate an ActionEvent with the
same action command. For example, clicking the Red button and selecting Red
from the menu both generate an ActionEvent with a Red action command.
import java.awt.*;
import javax.swing.*;
public class MenuDemo extends JFrame
{
private JButton red, blue, white;
private JProgressBar progress;
public MenuDemo(String title)
{
super(title);
Container contentPane = this.getContentPane();
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
red = new JButton(“Red”);
blue = new JButton(“Blue”);
white = new JButton(“White”);
Search WWH ::




Custom Search