Java Reference
In-Depth Information
In a menu, the items or separators are added from top to bottom in the order of
the add commands.
8.2.3
Menu items
From JMenuItem we need the constructor which receives the item title in a string
and a method to assign an action listener to the menu item. Menu items behave
much like buttons. In particular, the action listener is automatically informed
when the item is clicked on. The listener then starts the desired actions. Finally
we need a method to enable or disable a menu item:
JMenuItem(String itemText)
addActionListener(ActionListener listener)
setEnabled( boolean b)
The call setEnabled(false) disables a menu item. The item appears with a lighter
text and any listener assigned to it is no longer informed when the item is clicked
on. Hence, a disabled item does not trigger any reaction in the application. Call-
ing setEnabled(true) will enable the item again. Its text becomes darker and
listeners assigned to the item are again informed of events.
8.2.4
Constructing the GUI
We are now able to implement the GUI. The listings below show the code for the
frame class MenuFrame and the driver class MenuDriver .A MenuFrame has a label
centrally placed in its content pane. A menu bar is created and added. Then the
two menus are created and added. Finally we generate the menu items and add
them to the respective menus. Finally an action listener is created and assigned
to all menu items. This listener is an instance of the class MenuListener which
we define later in Section 8.3. The frame class also has three public methods for
setting the text in the label, and enabling or disabling the menu item 'Test' in the
first menu:
setText(String text)
enableTest()
disableTest()
File: its/Menus/MenuFrame.java
1.
package its.Menus;
2.
3.
import its.SimpleFrame.SimpleFrame;
import javax.swing.*;
4.
import java.awt.BorderLayout;
5.
6.
7.
public class MenuFrame extends SimpleFrame {
8.
Search WWH ::




Custom Search