Java Reference
In-Depth Information
private
JMenuBar menuMB =
new
JMenuBar();
//creates a menu bar
setJMenuBar(menuMB);
//sets the menu bar
Once you have created a menu bar, you can add menus, and in each menu you can add
menu items. For instance, to create an
Edit
menu and add it to the menu bar created
above, you need the following two statements:
JMenu editM =
new
JMenu("Edit");
//creates a menu "Edit"
menuMB.add(editM);
//adds the menu to menu bar
//menuMB created above
Likewise, if you need to create a
File
menu, you may do so by adding the following
lines of code:
JMenu fileM =
new
JMenu("File");
menuMB.add(fileM);
Notice that the order in which you add menus to the menu bar determines the order in
which they appear. For example, if you want the
File
menu to appear first, you must
add it first.
The following program illustrates the use of menus:
import
java.awt.*;
import
java.awt.event.*;
import
javax.swing.*;
public class
TextEditor
extends
JFrame
implements
ActionListener
{
private
JMenuBar menuMB =
new
JMenuBar();
//create the menu bar
private
JMenu fileM, editM, optionM;
private
JMenuItem exitI;
private
JMenuItem cutI, copyI, pasteI, selectI;
private
JTextArea pageTA =
new
JTextArea();
private
String scratchpad = "";
1
2
public
TextEditor()
{
setTitle("Simple Text Editor");
Container pane = getContentPane();
pane.setLayout(
new
BorderLayout());
pane.add(pageTA, BorderLayout.CENTER);
pane.add(
new
JScrollPane(pageTA));
pageTA.setLineWrap(
true
);
Search WWH ::
Custom Search