开发者

Jpopup not working for the ESc key

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 te开发者_C百科sted except for Esc key. How can i enable it ?


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);


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());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜