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");
}
}
}
}
但是,当我按下删除按钮时,看不到“按键”删除\“按下”消息!
答案 0 :(得分:5)
JFrame (all Top-Level Containers)永远不会对KeyEvents
做出反应,必须将此Listener
用于JComponent
consume Focus,或者可能用setFocusable()
不要对Swing JComponents使用low_level KeyListener,如果可以使用高级抽象,则使用KeyBindings代替
答案 1 :(得分:3)
JRootPane + KeyBindings(正如@mKorbel已经说过的那样)
String KEY = "UserPageAction";
f.getRootPane().getActionMap().put(KEY, action);
InputMap im = f.getRootPane().getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
同时退房:JMenuItem #setAccelerator(...)
JMenuItem item = new JMenuItem(action);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
SSCCE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UserPageTest {
public static JMenuBar makeMenuBar() {
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Test");
JMenuItem item = new JMenuItem(action);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
menu.add(item);
bar.add(menu);
return bar;
}
public static Action action = new AbstractAction("UserPage?") {
@Override public void actionPerformed(ActionEvent e) {
System.out.println("UserPage Action");
}
};
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() { createAndShowGUI(); }
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
String KEY = "UserPageAction";
f.getRootPane().getActionMap().put(KEY, action);
InputMap im = f.getRootPane().getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setJMenuBar(makeMenuBar());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}