我正在尝试在JPanel上使用Java进行密钥绑定。当我按下“w”按钮时,我想要执行某个动作。我按照Java教程进行绑定,但actionPerformed方法不执行(即没有文本打印出来)。以下是我的测试GUI的全部代码,相关部分突出显示:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
@SuppressWarnings("serial")
public class Test extends JFrame{
private JPanel panel;
public Test(){
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setLayout(new BorderLayout());
setVisible(true);
panel = new JPanel();
// HERE ARE THE KEY BINDINGS
panel.getInputMap().put(KeyStroke.getKeyStroke('w'),"forward");
panel.getActionMap().put("forward", new AbstractAction(){
@Override
public void actionPerformed(ActionEvent e){
System.out.println("test");
}
});
// END OF KEY BINDINGS
add(panel, BorderLayout.CENTER);
}
public static void main(String[] args){
new Test();
}
}
永远不会打印文本“test”。我尝试过多次使用许多不同的变体,不同的键,我确保面板是焦点,但没有运气。我究竟做错了什么?
答案 0 :(得分:19)
问题在于您查找KeyStroke
的方式。 KeyStroke.getKeyStroke('w')
将返回typed w
,由于某种原因,它不会触发关键事件。这就是为什么我倾向于避免这种方法。而是使用
panel.getInputMap().put(KeyStroke.getKeyStroke("W"),"forward");
或
panel.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0),"forward");
此外,您可能希望为InputMap
定义焦点约束,例如
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)...
会更安全......但你需要决定你希望从
触发击键的级别有关详细信息,请参阅JComponent
和How to use Key Bindings
更新了示例
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test extends JFrame {
private JPanel panel;
public Test() {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setLayout(new BorderLayout());
setVisible(true);
panel = new JPanel();
// HERE ARE THE KEY BINDINGS
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "forward");
panel.getActionMap().put("forward", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("test");
}
});
// END OF KEY BINDINGS
add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
new Test();
}
});
}
}