简体   繁体   English

Jpopup无法用于ESc密钥

[英]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. 通常,使用Esc键可隐藏菜单。.但是,在我的情况下,单击Esc键时必须显示菜单。 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. 对于我测试过的所有键(Esc键除外)都可以正常工作。 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. 它几乎就像Escape键一样也被转发到菜单,因此一旦打开它就会自动关闭。

Anyway, the proper way to do this is to use Key Bindings, NOT a KeyListener. 无论如何,执行此操作的正确方法是使用键绑定,而不是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: 只需使用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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM