由于我已经为我的 JFrame 中的每个 JPanel 添加了绑定,因此我会假设在我按下W
键时至少会触发其中一个。我的KeyStroke
不正确吗?
SSCCE:
public class TestTemp extends JFrame {
public TestTemp() {
setSize(1000, 800);
JPanel parentPanel = new JPanel(new MigLayout("", "grow, fill",
"grow, fill"));
parentPanel.setBackground(Color.GREEN);
setContentPane(parentPanel);
parentPanel.setSize(1000, 800);
JPanel videoPanel = new JPanel();
videoPanel.setBackground(Color.CYAN);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new MigLayout("fillx", "[fill]", "[nogrid]"));
contentPanel.setBackground(Color.YELLOW);
parentPanel.getInputMap().put(KeyStroke.getKeyStroke("W"), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("W pressed, parent panel");
}
});
contentPanel.getInputMap().put(KeyStroke.getKeyStroke("W"), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("W pressed, content panel");
}
});
videoPanel.getInputMap().put(KeyStroke.getKeyStroke("W"), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("W pressed, video panel");
}
});
parentPanel.add(videoPanel, "wmin 200");
parentPanel.add(contentPanel);
}
public static void main(String[] args) {
JFrame frame = new TestTemp();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
编辑:我尝试parentPanel
使用以下方法集中注意力:
parentPanel.setFocusable(true);
parentPanel.requestFocus();
但它似乎没有任何效果。
编辑2:为了确保它不是不正确的击键,我使用了文档在他们的示例中给出的击键:
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)
但同样,击球Enter
没有效果。