Question

I need shortcuts for the JMenuItems in JPopupMenu. In the code given below Shortcuts are not working.

import java.awt.event.*;
import javax.swing.*;
import static java.awt.event.InputEvent.CTRL_DOWN_MASK;

public class test3 implements ActionListener {

    JPopupMenu pop;

    void gui() {
        JFrame f = new JFrame();

        pop = new JPopupMenu();
        JMenuItem it1 = new JMenuItem("new");
        JMenuItem it2 = new JMenuItem("old");
        it1.setAccelerator(KeyStroke.getKeyStroke('N', CTRL_DOWN_MASK));
        it2.setAccelerator(KeyStroke.getKeyStroke('O', CTRL_DOWN_MASK));
        it1.addActionListener(this);
        it2.addActionListener(this);
        pop.add(it1);
        pop.add(it2);
        JTextArea ta = new JTextArea(20, 40);
        ta.add(pop);

        ta.addMouseListener(new MouseAdapter() {

            public void mousePressed(MouseEvent me) {
                if (me.isPopupTrigger()) {
                    pop.show(me.getComponent(), me.getX(), me.getY());
                }
            }

            public void mouseReleased(MouseEvent me) {
                if (me.isPopupTrigger()) {
                    pop.show(me.getComponent(), me.getX(), me.getY());
                }
            }
        });

        f.add(ta);
        f.pack();

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getActionCommand().equals("new")) {
            System.out.println("new");
        } else if (ae.getActionCommand().equals("old")) {
            System.out.println("old");
        }

    }

    public static void main(String[] argv) {
        test3 t = new test3();
        t.gui();
    }
}
Was it helpful?

Solution

The only problem with the code that you posted is a syntax error. Otherwise it is working. CTRL_DOWN_MASK is a constant in the KeyEvent class so you need to state that:

    KeyEvent.CTRL_DOWN_MASK

So the line should be:

    it1.setAccelerator(KeyStroke.getKeyStroke('N', KeyEvent.CTRL_DOWN_MASK)); 

And remove the static import line from your code. That should compile and work as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top