Java Reference
In-Depth Information
This creates a menu item as a
JMenuItem
object with the label
"New"
, adds it to the menu represented by
the
fileMenu
object, and returns a reference to the menu item. You need the reference to the menu item to
enable the program to react to the user clicking the item.
You can also create the
JMenuItem
object explicitly and use another version of the
add()
method for the
JMenu
object 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
JMenuItem
class methods:
•
void setEnabled(boolean b)
: If
b
has the value
true
, the menu item is enabled;
false
makes
it. 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.
Because the
JMenu
class is a subclass of
JMenuItem
, these methods also apply to
JMenu
objects.
To add a separator to a menu you call the
addSeparator()
method for the
JMenu
object. The separator
appears following the previous menu item that you added to the menu.
Let's now create the drop-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 Drop-Down Menus
You can change the definition of our
SketcherFrame
class to do this:
// Frame for the Sketcher application
import javax.swing.*;
public class SketcherFrame extends JFrame {
// Constructor
public SketcherFrame(String title) {
setTitle(title); // Set the window
title
setDefaultCloseOperation(EXIT_ON_CLOSE);
setJMenuBar(menuBar); // Add the menu bar
to the window
JMenu fileMenu = new JMenu("File"); // Create File menu
JMenu elementMenu = new JMenu("Elements"); // Create Elements
menu
// Construct the file drop-down menu
newItem = fileMenu.add("New");
// Add New item
openItem = fileMenu.add("Open");
// Add Open item
closeItem = fileMenu.add("Close");
// Add Close item