Q:

Invoking a MenuItem with one keystroke

We know that we can invoke a menu item with the help of setaccelerator() method where a combination of two keystrokes are required. what if i want to invoke a menu item by just one keystroke...here is where i am having a bit problem
menuitem=new JMenuItem("Delete");
menuitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE);        
menu.add(menuitem);

Please help....!!

A:

Check How to Use Menus for details. Below is an example that utilizes Action, that defines accelerator. You can also set accelerator on the menu item, ie: item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));. 
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class MenuDemo {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                final JFrame frame = new JFrame("Demo");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JMenuBar menuBar = new JMenuBar();
                JMenu menu = new JMenu("Menu");
                menuBar.add(menu);

                JMenuItem item = new JMenuItem(new TestAction(frame));

                menu.add(item);

                frame.setJMenuBar(menuBar);

                frame.setSize(new Dimension(300, 300));
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }

    static class TestAction extends AbstractAction {
        private Component parent;

        public TestAction(Component parent) {
            super("Test");
            this.parent = parent;
            putValue(Action.ACCELERATOR_KEY,
                    KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(parent, "Test");
        }
    }
}

