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);
            }
        });
    }

}
4

1 回答 1

5
于 2013-07-19T15:43:32.943 回答