learning java AWT MenuBar Menu MenuItem菜单
import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class SimpleMenu { private Frame f = new Frame("test"); private MenuBar mb = new MenuBar(); Menu file = new Menu("file"); Menu edit = new Menu("edit"); MenuItem crateItem = new MenuItem("create"); MenuItem saveItem = new MenuItem("save"); MenuItem exitItem = new MenuItem("exit", new MenuShortcut(KeyEvent.VK_X)); CheckboxMenuItem autoWrap = new CheckboxMenuItem("autoWrap"); MenuItem copyItem = new MenuItem("copy"); MenuItem pasteItem = new MenuItem("paste"); Menu format = new Menu("format"); /*ctrl + shift + / */ MenuItem commentItem = new MenuItem("comment", new MenuShortcut(KeyEvent.VK_SLASH,true)); MenuItem cancelItem = new MenuItem("cancelComment"); private TextArea ta = new TextArea(6,40); public void init(){ ActionListener menuListener = e -> { var cmd = e.getActionCommand(); ta.append(" click " + cmd + " menu " + " \n "); if(cmd.equals("exit")){ System.exit(0); } }; commentItem.addActionListener(menuListener); exitItem.addActionListener(menuListener); file.add(crateItem); file.add(saveItem); file.add(exitItem); edit.add(autoWrap); edit.addSeparator(); edit.add(copyItem); edit.add(pasteItem); format.add(commentItem); format.add(cancelItem); edit.add(new MenuItem("-")); edit.add(format); mb.add(file); mb.add(edit); f.setMenuBar(mb); f.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); f.add(ta); f.pack(); f.setVisible(true); } public static void main(String[] args) { new SimpleMenu().init(); } }
output: