您的示例仅在面板具有焦点时才有效,请尝试使用getInputMap(WHEN_IN_FOCUSED_WINDOW)
。
您可能还会发现您的KeyStroke
语句也不起作用,我建议您尝试使用KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true)
它,这将为您提供一个KeyStroke
响应关键版本的对象。
更新了示例
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestKeyBindings04 {
public static void main(String[] args) {
new TestKeyBindings04();
}
public TestKeyBindings04() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false), "pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true), "released");
am.put("pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Pressed");
}
});
am.put("released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("released");
}
});
setFocusable(true);
requestFocusInWindow();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
}