《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();
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenuItem exitItem = new JMenuItem("Exit");
JButton compButton = new JButton(
"show menubar components ...");
JButton menuButton = new JButton(
"show menubar menus ...");
fileMenu.add("New ...");
fileMenu.add("Open ...");
fileMenu.add("Save");
fileMenu.add("Save As ..");
fileMenu.addSeparator();
fileMenu.add(exitItem);
editMenu.add("Undo");
editMenu.addSeparator();
editMenu.add("Cut");
editMenu.add("Copy");
editMenu.add("Paste");
mb.setMargin(new Insets(30,20,10,5));
mb.add(new JLabel(new ImageIcon("smiley.gif")));
mb.add(fileMenu);
mb.add(editMenu);
setJMenuBar(mb);
contentPane.setLayout(new FlowLayout());
contentPane.add(compButton);
contentPane.add(menuButton);
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component c;
int cnt = mb.getMenuCount();
for(int i=0; i < cnt; ++i) {
c = mb.getMenu(i);
System.out.println(c);
System.out.println();
}
}
});
compButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component c;
int cnt = mb.getComponentCount();
for(int i=0; i < cnt; ++i) {
c = mb.getComponentAtIndex(i);
System.out.println(c);
System.out.println();
}
}
});
}
}