Listening for key strokes in a nested panel

落爺英雄遲暮 提交于 2019-12-12 16:14:40

问题


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

}

回答1:


  • see Oracle tutorial How to use KeyBindings

  • you miss there set focus to JPanel panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(...)



来源:https://stackoverflow.com/questions/17750088/listening-for-key-strokes-in-a-nested-panel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!