Jpopup 不适用于 ESc 键
一般来说,Esc 键用于隐藏菜单。但就我而言,我必须在单击 Esc 键时显示菜单。 我有一个组合 我正在执行以下操作
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();
}
}
这对于我测试的所有键(Esc 键除外)都适用。我怎样才能启用它?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它几乎就像 Escape 键也被转发到菜单,因此一旦打开它就会自动关闭。
无论如何,正确的方法是使用键绑定,而不是 KeyListener。阅读我关于按键绑定的介绍,使用链接中的建议你的代码是:
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:
只需使用 KeyEvent.VK_ESCAPE:
Just consume the KeyEvent.VK_ESCAPE: