《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JApplet {
public void init() {
Container contentPane = getContentPane();
final JMenuBar mb = new JMenuBar();
final MenuBarPrinter printer = new MenuBarPrinter();
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.setMnemonic('F');
editMenu.setMnemonic('F');
fileMenu.add("New ...");
fileMenu.add("Open ...");
fileMenu.add("Save");
fileMenu.add("Save As ..");
fileMenu.addSeparator();
fileMenu.add(exitItem);
editMenu.add("Cut");
editMenu.add("Copy");
editMenu.add("Paste");
mb.add(fileMenu);
mb.add(editMenu);
setJMenuBar(mb);
JButton button = new JButton("show menu information");
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
printer.print(mb);
}
});
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
class MenuBarPrinter {
static public void print(JMenuBar menubar) {
int numMenus = menubar.getMenuCount();
JMenu nextMenu;
JMenuItem nextItem;
System.out.println();
System.out.println("MenuBar has " +
menubar.getMenuCount() +
" menus");
System.out.println();
for(int i=0; i < numMenus; ++i) {
nextMenu = menubar.getMenu(i);
System.out.println(nextMenu.getText() + " menu ...");
System.out.println(nextMenu);
int numItems = nextMenu.getItemCount();
for(int j=0; j < numItems; ++j) {
nextItem = nextMenu.getItem(j);
System.out.println(nextItem);
}
System.out.println();
}
}
}