Adding Menus to Your Program

paltryboarpigSoftware and s/w Development

Nov 3, 2013 (3 years and 9 months ago)

49 views

Adding Menus to Your Program


You can add a menu system to any JFrame window. Before looking

at the code necessary to make a menu system work, let's go over

some of the language involved. Make sure that you keep the following

terms straight as this
document progresses (of course, now that I have

warned you, I am sure that I will mess things up…I'll do my best).


Menu



a
menu

is one drop
-
down with a title and entries in it. In

the
top
image
on

the right, there is only one
menu
: the "File"

menu.

In
the second image, I have clicked on the File
menu

to

show its contents
: Save and Open
.

The contents of a
men
u

are

called
menu items
.
In the bottom image, there

are two

menus
: File and Help.
A
menu

lives inside of a
menu bar
.

A program
can have multiple
menus
, but typically has one
menu bar
.


MenuItem



a
menu item

is an entry found inside of a
menu
. Each
menu

must have at least one
menu item

in it (otherwise it would be empty).

In the second image, there are two
menu items

inside of the

File
menu
: Save

and Open.

In the bottom image, there are two

menu items

inside of the Help
menu
: Updates and About.


MenuBar



the
menu bar

is the ribbon across the top of the JFrame

(but below the title bar) that holds all of the various
menus
.

I have Word open right now and I see 8
menus

in my

menu bar
. In the

top

image, there is only one
menu

in
the menu

bar
; the rest of the
menu bar

is gray
, like the background,

but it is

visible in the
image due to a faint separator line.

In the bottom

im
age,
there are two
menus

in the
menu bar
: File and Help
.
Again,

a program

typically

has one
menu bar
, but can have multiple
menus
.


When you make a menu system, you want to decide which menus to create.

Typical menus are "File", "Edit", "View", etc. For each menu, decide which

menu items to put inside of the menu.

You only add menu items to a single

menu. For example, the "Updates" and "About" menu items were added to

the "Help" menu in the bottom pictu
re. Finally, after you have created menus and adding menu items to them, you will
add the menus to the menu bar. (You do not add menu items to the menu bar.)


tl;dr


add menu items to menus and then add menus to the menu bar.


So…let's see some code!

Addi
ng a menu system to a JFrame is

actually pretty simple. In this first example, I will add menus to a subclass of
JFrame.

Note that this

code adds the menu system inside of the class' constructor and then handles user
-
input inside of the
actionPerformed() m
ethod (similar to working with buttons and other GUI objects).

If you don't remember how to handle
button events, please review the relevant document.



import java.awt.*;




//nothing new to import…kind of standard imports for our GUI stuff

import java.aw
t.event.*;

import javax.swing.*;


public class MyFirstMenu extends JFrame implements ActionListener

{


public MyFirstMenu()


{



super("title");



setDefaultCloseOperation(EXIT_ON_CLOSE);









//create two menus
…the String parameter is the text you will

see on the menu



JMenu fileMenu = new JMenu("File");



JMenu helpMenu = new JMenu("Help");









//
1)
create the

menu items

for the "File" menu
,
2)
configure them
for use wi
th actionPerformed(),

//
and then
3)
add them to the "File" menu


1)

JMenuItem
save = new JMenuItem("Save");



JMenuItem open = new JMenuItem("Open");





2)

save.setActionCommand("save");



open.setActionCommand("open");



save.addActionListener(this);



open.addActionListener(this);





3)

fileMenu.add(save);



fileMenu.add(open);









//
1)
create "H
elp" menu items, 2) configure them
for use with actionPerformed(), and then



//
3)
add them to the "Help" menu


1)

JMenuItem updates = new JMenuItem("Updates");



JMenuItem about = new JMenuItem("About");





2)

updates.setActionCommand("updates");



about.setActionCommand("about");



updates.addActionListener(this);



about.addActionListener(this);





3)

helpMenu.add(updates);



helpMenu.add(about);









//create the menu bar and add the menus

to the menu bar



JMenuBar menuBar = new J
m
enuBar();



menuBar.add(fileMenu);



menuBar.add(helpMenu);



//add the menu bar to the J
f
rame itself



setJMenuBar(menuBar);









//set size and show the J
f
rame
…nothing new here



setSize(500,500);



setVisible(true);


}





//This class handles menu events like our button handling code handled button events


public void actionPerformed(ActionEvent evt)


{

//get the action command (unique keyword) associated with this event



String actionCmd = evt.getActionCommand();





//check to see which event based upon which keyword
…not doing much once we find it, but that is up to
//you to work out. There is another document that shows you how to save files and open files for reading.



if(actionCmd.equals("save"))



{




JOptionPan
e.showMessageDialog(null,





"Saving not implemented yet");



}



else if(actionCmd.equals("open"))



{




JOptionPane.showMessageDialog(null,





"Opening files not implemented yet");



}



else if(actionCmd.equals("updates"))



{




JOptionPane.showMe
ssageDialog(null,





"Visit http://www.google.com for blah");



}



else if(actionCmd.equals("about"))



{




JOptionPane.showMessageDialog(null,





"
\
"I made this!
\
"
\
n
--
Mike Maunu");



}


}



//simple main method to run the program…it just makes the
main JFrame object, which takes care of the rest


public
static void main(String[] args)
{



MyFirstMenu
mfm

= new MyFirstMenu();


}

}


Extension
: add an "Edit" menu with "Undo" and "Find" as menu items. When the user (probably you) selects one of
these
options, they should get some kind of message indicating that the item's functionality is still being worked on.

Keyboard Shortcuts

You might want to add keyboard shortcuts to your menu system. There are two types of shortcuts:
accelerator

keys and
mnemoni
c

keys.


Accelerator

keys are the typical
Ctrl+O

or
Ctrl+S

shortcuts for opening and saving files (or
Ctrl+P

for printing,
Ctrl+C
for Copying,
Ctrl+V

for Pasting, etc.).
These are great features to add to any menu system.


Mnemonic

keys are used in conjun
ction with the
Alt

key to bring up menus and select menu options

(widely
available in programs if you are running Windows…usually not present in programs on Macs)
. If you haven't
used the Alt key before,
and you are running Windows,
open up a program like
Firefox or Chrome

and press the
Alt key. Notice that this
highlights
a
single
letter in each of the menus

(typically by putting

an underline

beneath

the letter)
. Now press that underlined letter on the keyboard and the menu will open up. Notice that the me
nu
items similarly have a
highlighted

letter; press one
of the highlighted letters (on your keyboard)
to activate the
menu option.)


You can set BOTH accelerators and mnemonics for JMenuItems
but

you can
only
set mnemonics for
JMenus
. Note that

you can'
t s
et either for the JMenuBar.



Accelerator Code

for a JMenuItem

This sets Ctrl+O as the keyboard shortcut for the
"O
pen
"

JMenuItem

(which is a variable called
open
)
.


open.set
Accelerator
( KeyStroke.getKeyStroke( KeyEvent.VK_O, ActionEvent.CTRL_MASK ));


To

change this

to Ctrl+S
, simply
change the VK_O to
VK_S.
(VK stands for Virtual Key, by the way.)


If you want an Alt+F4 shortcut, change VK_O to
VK_F4 and CTRL_MASK to ALT_MASK.




Mnemonic Code

for a JMenuItem

open.set
Mnemonic
( ‘O’ );




Mnemonic
Code
for a JMenu:

fileMenu.setMnemonic( 'F' );


With those mnemonics set, you can use Alt
-
F to open the file menu and then just tap "O" to activate the "Open"
menu item. You do not need to capitalize the F and the O when typing these shortcuts. Also, recall tha
t this is
typically only used on Windows
machines
.


Fun Fact

You can set mnemonics for buttons and then activate the buttons with your keyboard (rather than clicking on the
button).

Try it!!

It literally only takes one line of code

(you don't have to modif
y
any
button
-
handling code)
:

someB
utton.setMnemonic( 'O' );


Hitting Alt
-
O will now act as a button click (for the button variable called
someB
utton
).