import java.awt.Component;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
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.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class ActionMenuSample {
public static class ShowAction extends AbstractAction {
Component parentComponent;
public ShowAction(Component parentComponent) {
super("About");
putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_A));
this.parentComponent = parentComponent;
}
public void actionPerformed(ActionEvent actionEvent) {
Runnable runnable = new Runnable() {
public void run() {
JOptionPane.showMessageDialog(parentComponent,
"About Life", "About Box V1.0",
JOptionPane.INFORMATION_MESSAGE);
}
};
SwingUtilities.invokeLater(runnable);
}
}
public static void main(String args[]) {
JFrame frame = new JFrame("Action Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Action showAction = new ShowAction(frame);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('f');
JMenuItem newMenuItem = new JMenuItem("New", 'N');
fileMenu.add(newMenuItem);
JMenuItem openMenuItem = new JMenuItem("Open", 'O');
fileMenu.add(openMenuItem);
JMenuItem closeMenuItem = new JMenuItem("Close", 'C');
fileMenu.add(closeMenuItem);
fileMenu.addSeparator();
JMenuItem saveMenuItem = new JMenuItem("Save", 'S');
fileMenu.add(saveMenuItem);
fileMenu.add(showAction);
fileMenu.addSeparator();
JMenuItem exitMenuItem = new JMenuItem("Exit", 'X');
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
JMenu editMenu = new JMenu("Edit");
JMenuItem cutMenuItem = new JMenuItem("Cut", 'T');
KeyStroke ctrlXKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_X,
Event.CTRL_MASK);
cutMenuItem.setAccelerator(ctrlXKeyStroke);
editMenu.add(cutMenuItem);
JMenuItem copyMenuItem = new JMenuItem("Copy", 'C');
KeyStroke ctrlCKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C,
Event.CTRL_MASK);
copyMenuItem.setAccelerator(ctrlCKeyStroke);
editMenu.add(copyMenuItem);
JMenuItem pasteMenuItem = new JMenuItem("Paste", 'P');
KeyStroke ctrlVKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V,
Event.CTRL_MASK);
pasteMenuItem.setAccelerator(ctrlVKeyStroke);
pasteMenuItem.setEnabled(false);
editMenu.add(pasteMenuItem);
editMenu.addSeparator();
JMenuItem findMenuItem = new JMenuItem("Find", 'F');
KeyStroke f3KeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0);
findMenuItem.setAccelerator(f3KeyStroke);
editMenu.add(findMenuItem);
editMenu.setMnemonic('e');
editMenu.add(showAction);
menuBar.add(editMenu);
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
|