Java Reference
In-Depth Information
Adding Items to a Pull-Down Menu
Both the items on the menu bar need a pull-down menu - they can't do anything by themselves because
they are of type JMenu . You use a version of the add() method defined in the JMenu class to add
items to a pull-down menu.
The simplest version creates a menu item with the label that you pass as an argument. For example:
JMenuItem newMenu = fileMenu.add("New"); // Add the menu item "New"
This will create a JMenuItem object with the label " New ", add it to the menu for the fileMenu item,
and return a reference to it. You will need the reference to react to the user clicking the item.
You can also create the JMenuItem object explicitly and use the second version of the add() method
to add it:
JMenuItem newMenu = new JMenuItem("New"); // Create the item
fileMenu.add(newMenu); // and add it to the menu
You can operate on menu items by using the following methods defined in the JMenuItem class:
Method
Description
void setEnabled(
boolean b)
If b has the value true the menu item is enabled. If b has the value
false the menu item is disabled. The default state is enabled.
void setText(
String label)
Sets the menu item label to the string stored in the label.
String getText()
Returns the current menu item label.
Since the JMenu class is a subclass of JMenuItem , these methods also apply to JMenu objects. To add
a separator to a pull-down menu you call the addSeparator() method for the JMenu object.
Let's now create the pull-down menus for the File and Element menus on the menu bar in the Sketcher
application, and try out some of the menu items.
Try It Out - Adding Pull-Down Menus
We can change the definition of our SketchFrame class to do this:
// Frame for the Sketcher application
import javax.swing.*;
public class SketchFrame extends JFrame {
// Constructor
public SketchFrame(String title) {
setTitle(title); // Set the window title
setDefaultCloseOperation(EXIT _ ON _ CLOSE);
Search WWH ::




Custom Search