java在JFrame中创建快捷方式
public final class UserPage extends JFrame{
public UserPage() {
this.addKeyListener(new myclass());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000, 600);
this.setLocation(300, 60);
this.setResizable(false);
this.setVisible(true);
}
.
.
.
public class myclass extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
System.out.println("Key \"Delete\" Pressed");
}
}
}
}
但是,当我按下删除按钮时,看不到“按键”删除“按下”消息
# 1 楼答案
JRootPane+键绑定(正如@mKorbel已经说过的)
还可以查看:JMenuItem#setAccelerator(…)
SSCCE
# 2 楼答案
JFrame (all Top-Level Containers)默认情况下,决不对
KeyEvents
作出反应,必须使用此Listener
来表示JComponent
他们将consume Focus,或者可以用setFocusable()
来标记它不要对Swing JComponents使用低级KeyListener,如果可能的话,使用高级抽象,而是使用KeyBindings