Menus: Main.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main extends JFrame implements ActionListener { //*5 ActionListener for each item
    // Remember them in ivars for use in callback
    private MyModel myModel; //*8 Main points to MyCanvas and MyModel via ivars, Canvas points to MyModel
    private MyCanvas canvas; //*8

    public static void main (String [] args) {
	java.awt.EventQueue.invokeLater (new Runnable() {
            public void run() {
		new Main ();
            }
        });
    }

    public Main () {
	// Window setup
	setLocation (100, 100);
	setSize (300, 300);
	setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
	Container content = getContentPane();

	// Holds our data
	myModel = new MyModel ("Waiting for menu item"); //*8

	// Put canvas in our window
	canvas = new MyCanvas (myModel); //*8
	content.add (canvas);

	// Add a menu to our window
	JMenu menu = new JMenu ("File"); //*1 Create a JMenu object with title word
	
	// And its items
	JMenuItem item = new JMenuItem ("Open"); //*2 Create each JMenuItem and add to JMenu
	menu.add (item); //*2
	item.addActionListener (this); //*5

	item = new JMenuItem ("Save"); //*2
	menu.add (item); //*2
	item.addActionListener (this); //*5

	item = new JMenuItem ("Quit"); //*2
	menu.add (item); //*2
	item.addActionListener (this); //*5

	// Add menu to a menu bar
	JMenuBar menuBar = new JMenuBar (); //*3 Create a JMenuBar object and add our menus
	menuBar.add (menu); //*3

	// Another menu
	JMenu menu2 = new JMenu ("Edit"); //*1

	// Some items for menu2
	item = new JMenuItem ("Cut"); //*2
	menu2.add (item); //*2
	item.addActionListener (this); //*5

	item = new JMenuItem ("Copy"); //*2
	menu2.add (item); //*2
	item.addActionListener (this); //*5

	item = new JMenuItem ("Paste"); //*2
	menu2.add (item); //*2
	item.addActionListener (this); //*5

	// Add menu2 to the menu bar
	menuBar.add (menu2); //*3

	// Install menu bar in our window
	setJMenuBar (menuBar); //*4 Install menu bar in our window

	setVisible (true);
    }

    // ActionListener method for all the pull-down menu items
	public void actionPerformed (ActionEvent e) { //*5
	if (e.getActionCommand().equals ("Quit")) { //*7 Or just exit
	    System.exit (0); //*7
	}

	else {
	    // Change the text
	    myModel.setText ("Menu item: " + e.getActionCommand()); //*6 How to change drawing area

	    // Then trigger a redraw
	    canvas.repaint (); //*6
	}
    }
}
[download file]