《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JApplet {
public void init() {
JMenuBar mb = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem newItem = new JMenuItem("New ..."),
openItem = new JMenuItem("Open ..."),
saveItem = new JMenuItem("Save"),
saveAsItem = new JMenuItem("Save As ..."),
exitItem = new JMenuItem("Exit");
Listener listener = new Listener(this);
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(saveAsItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
newItem.setActionCommand("Create a New Document");
openItem.setActionCommand("Open an Existing Document");
saveItem.setActionCommand("Save Document");
saveAsItem.setActionCommand("Save Document As ...");
exitItem.setActionCommand("Exit the applet");
newItem.addChangeListener(listener);
openItem.addChangeListener(listener);
saveItem.addChangeListener(listener);
saveAsItem.addChangeListener(listener);
exitItem.addChangeListener(listener);
mb.add(fileMenu);
setJMenuBar(mb);
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
class Listener implements ChangeListener {
private JApplet applet;
public Listener(JApplet applet) {
this.applet = applet;
}
public void stateChanged(ChangeEvent e) {
JMenuItem b = (JMenuItem)e.getSource();
if(b.isArmed())
applet.showStatus(b.getActionCommand());
}
}