GUI菜单:
package gui.test07;
import java.awt.CheckboxMenuItem;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestMenuBar extends Frame {
MenuBar menuBar = new MenuBar();
Menu fileM = new Menu("File");
Menu editM = new Menu("Edit");
Menu toolsM = new Menu("Tools");
Menu helpM = new Menu("Help");
MenuItem fileM1 = new MenuItem("New");
MenuItem fileM2 = new MenuItem("Open");
MenuItem fileM3 = new MenuItem("Save");
Menu fileM4 = new Menu("print");
MenuItem printM1 = new MenuItem("preview");
MenuItem printM2 = new MenuItem("setting");
CheckboxMenuItem fileM5 = new CheckboxMenuItem("Quit",true);
public TestMenuBar() {
menuBar.add(fileM);
menuBar.add(editM);
menuBar.add(toolsM);
menuBar.add(helpM);
fileM.add(fileM1);
fileM.add(fileM2);
fileM.add(fileM3);
fileM.add(fileM4);
fileM.addSeparator();
fileM.add(fileM5);
fileM4.add(printM1);
//设置actionCommand,若不设置,默认为菜单上的label文本
printM1.setActionCommand("junlas");
fileM4.add(printM2);
ActionListener ml = new MenuListener();//菜单点击,抛出ActionEvent
printM1.addActionListener(ml);
printM2.addActionListener(ml);
this.setMenuBar(menuBar);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
public static void main(String[] args) {
TestMenuBar mainFrame = new TestMenuBar();
mainFrame.setSize(400, 400);
mainFrame.setTitle("TestMenuBar");
mainFrame.setVisible(true);
}
}
package gui.test07;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MenuListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("junlas")) {
System.out.println("doing junlas");
}else if(e.getActionCommand().equals("setting")){
System.out.println("doing setting");
}
}
}