3

In the Java file below, I create a frame containing a panel, which then nests a second panel. I'm trying to listen for key strokes in the nested panel. My approach is to use an input map and an action map. I've found if I only have an input map for the nested panel, things work as expected. However, if the parent panel also has an input map, key stroke events are not passed to the nested panel. You can observe this behavior by commenting and uncommenting the first call to getInputMap().put. Does anyone have a solution for this?

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class InputMapTest extends JPanel {

    public InputMapTest() {
        super(new BorderLayout());
        JPanel panel = new JPanel();
        KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        getInputMap().put(ks, "someAction");
        getActionMap().put("someAction", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("here1");
            }
        });
        ks = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0);
        panel.getInputMap().put(ks, "someOtherAction");
        panel.getActionMap().put("someOtherAction", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("here2");
            }
        });
        add(panel);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.getContentPane().add(new InputMapTest());
                frame.setSize(800, 600);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
David Struck
  • 157
  • 1
  • 9
  • Just to clarify, I had three responses to this question and they all suggested using key bindings. Am I not using key bindings in the above code? – David Struck Jul 22 '13 at 14:13
  • Doi.. And it clearly stated that in the words & code! Noise deleted. :P Glad you've got it sorted with the expert advice of @mKorbel. :) – Andrew Thompson Jul 22 '13 at 14:19

1 Answers1

5
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • This works, although in the problem I'm working on, I think using JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT for the parent panel is more appropriate. Thanks for pointing me in the right direction! – David Struck Jul 22 '13 at 14:12