Menu Events

When the user selects a menu item, the menu item fires an action event. This will be picked up by any action listeners registered on the menuI item. The action command is set to the text of the menu item selected.

For example, the following applet puts the text of each menu item selected in the text field theChoice.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;


public class ActiveMenuTester extends Applet implements ActionListener {

  TextField theChoice = new TextField(20); 

  public void init () {

    Frame f = new Frame("Simple Window");
    f.add("North", new Label("Look at the Menus", Label.CENTER));
    f.add("South", theChoice);
    f.setSize(300, 200);
    f.setLocation(220,240);
    MenuBar myMenuBar = new MenuBar();
    this.makeFileMenu(myMenuBar);
    this.makeEditMenu(myMenuBar);
    f.setMenuBar(myMenuBar);
    f.addWindowListener(new WindowCloser());
    f.show();

  }
  
  protected void addItem(Menu m, String s) {
  
    MenuItem mi = new MenuItem(s);
    mi.addActionListener(this);
    m.add(mi); 
    
  }
  
  protected void makeEditMenu(MenuBar mb) {
  
    Menu editMenu = new Menu("Edit");
    this.addItem(editMenu, "Undo");
    editMenu.addSeparator();
    this.addItem(editMenu, "Cut");
    this.addItem(editMenu, "Copy");
    this.addItem(editMenu, "Paste");
    this.addItem(editMenu, "Clear");
    mb.add(editMenu);
    
  }

  protected void makeFileMenu(MenuBar mb) {
  
    Menu fileMenu = new Menu("File");
    this.addItem(fileMenu, "New");
    this.addItem(fileMenu, "Open...");
    fileMenu.addSeparator();
    this.addItem(fileMenu, "Close");
    this.addItem(fileMenu, "Save");
    this.addItem(fileMenu, "Save As...");
    fileMenu.addSeparator();
    this.addItem(fileMenu, "Page Setup...");
    this.addItem(fileMenu, "Print");
    fileMenu.addSeparator();
    this.addItem(fileMenu, "Quit");
    mb.add(fileMenu);
    
  }
  
  
  public void actionPerformed(ActionEvent e) {
  
    theChoice.setText(e.getActionCommand());
  
  }
  
  class WindowCloser extends WindowAdapter {
  
    public void windowClosing(WindowEvent e) {
      Window w = (Window) e.getSource();
      w.setVisible(false);
      w.dispose();
    }
  
  }

}

Previous | Next | Top
Last Modified July 8, 1998
Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu