As I’ve added the binding for each JPanel which is in my JFrame, I would have assumed at least one of them to fire when I press the W key. Is my KeyStroke incorrect?
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);
}
}
Edit:
I attempted to give the parentPanel focus using:
parentPanel.setFocusable(true);
parentPanel.requestFocus();
but it appeared not to have any effect.
Edit 2:
To ensure it wasn’t an incorrect keystroke, I used the keystroke the docs give in their example:
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)
but again, hitting Enter had no effect.
Try this:
I don’t think MigLayout is the issue.
getActionMapinstead ofgetInputMapto wait for action events.InputMapto listen for keystrokes.The
enterkeyboard events are now written to standard output.See these links for details:
Generally speaking, when you encounter a difficult problem, try to make the simplest case work. Once you have the simplest case working (e.g., one panel accepting keyboard inputs), then build on the complexity. You could have even removed MigLayout, for example, to see if it was affecting the keyboard inputs.