tags:

views:

24

answers:

2

in general the Esc key is used to hide the menu.. but in my case i have to show a menu on click of an Esc key. I have a combo I am doing the following

public class MyFrame extends JFrame implements KeyListener{

JPopupMenu menu = new JPopupMenu();
JTextField txt = new JTextField("TestField1");
JTextField txt1 = new JTextField("TestField2");
public MyFrame(){
    init();
}
private void init(){

    setLayout(new BorderLayout());
    txt.addKeyListener(this);
    add( txt,BorderLayout.WEST);
    add(txt1,BorderLayout.CENTER);
    pack();
    setVisible(true);

}
@Override
public void keyPressed(KeyEvent e) {

    System.out.println("keypressed");

    menu = new JPopupMenu();
    menu.add("item1");
    menu.add("item2");
    menu.show(e.getComponent(),e.getComponent().getX(),e.getComponent().getY());
}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

public static void main(String args[]){
    new MyFrame();
}

}

This works fine for all the keys i tested except for Esc key. How can i enable it ?

+1  A: 

Its almost like the Escape key is also being forwarded to the menu so it closes automatically as soon as it is opened.

Anyway, the proper way to do this is to use Key Bindings, NOT a KeyListener. Read my intro on Key Bindings, Using the suggestion from the link your code would be:

Action action = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        menu = new JPopupMenu();
        menu.add("item1");
        menu.add("item2");
        Component component = (Component)e.getSource();
        menu.show(component, component.getX(), component.getY());
    }
};
String keyStrokeAndKey = "ESCAPE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
txt.getInputMap().put(keyStroke, keyStrokeAndKey);
txt.getActionMap().put(keyStrokeAndKey, action);
camickr
+1  A: 

Just consume the KeyEvent.VK_ESCAPE:

@Override
public void keyPressed(KeyEvent e) {
    System.out.println("keypressed");
    Component c = e.getComponent();
    if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
        e.consume();
    }
    menu.show(c, c.getX(), c.getY());
}
trashgod
@harshit: Note @camickr's solution is much more flexible. Also, the `menu.add()` can be moved to the constructor.
trashgod
nice to see two solutions :-) ..
harshit