Java Reference
In-Depth Information
Note that for this beginning example, none of the menu choices will do anything other
than print which menu choice was selected. For example, selecting the Copy option from the
Edit menu displays Selected: Copy .
Listing 6-1 shows the complete source for the class that generated the example in Figure 6-1.
Listing 6-1. The MenuSample Class Definition
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuSample {
static class MenuActionListener implements ActionListener {
public void actionPerformed (ActionEvent actionEvent) {
System.out.println ("Selected: " + actionEvent.getActionCommand());
}
}
public static void main(final String args[]) {
Runnable runner = new Runnable() {
public void run() {
ActionListener menuListener = new MenuActionListener();
JFrame frame = new JFrame("MenuSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
// File Menu, F - Mnemonic
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
// File->New, N - Mnemonic
JMenuItem newMenuItem = new JMenuItem("New", KeyEvent.VK_N);
newMenuItem.addActionListener(menuListener);
fileMenu.add(newMenuItem);
// File->Open, O - Mnemonic
JMenuItem openMenuItem = new JMenuItem("Open", KeyEvent.VK_O);
openMenuItem.addActionListener(menuListener);
fileMenu.add(openMenuItem);
// File->Close, C - Mnemonic
JMenuItem closeMenuItem = new JMenuItem("Close", KeyEvent.VK_C);
closeMenuItem.addActionListener(menuListener);
fileMenu.add(closeMenuItem);
Search WWH ::




Custom Search