[java]代码库
package day03;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
public class TestMenu {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new TestMenuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class TestMenuFrame extends JFrame{
public TestMenuFrame(){
setTitle("测试菜单");
setSize(300,400);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("文件");
menuBar.add(fileMenu);
JMenuItem newItem = fileMenu.add(new TestAction("新建"));
JMenuItem openItem= fileMenu.add(new TestAction("打开"));
fileMenu.addSeparator();
JMenuItem saveItem = fileMenu.add(new TestAction("保存"));
JMenuItem saveasItem = fileMenu.add(new TestAction("另存为"));
fileMenu.addSeparator();
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(exitItem);
exitItem.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
newItem.setAccelerator(KeyStroke.getKeyStroke("ctrl N"));
openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
}
}
class TestAction extends AbstractAction{
public TestAction(String name ){
super(name);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println(getValue(Action.NAME)+"selected.");
}
}