在嵌套面板中侦听击键

时间:2013-07-19 15:38:09

标签: java swing jpanel key-bindings

在下面的Java文件中,我创建了一个包含面板的框架,然后嵌套第二个面板。我正试图在嵌套面板中监听击键。我的方法是使用输入映射和动作映射。我发现如果我只有嵌套面板的输入映射,事情按预期工作。但是,如果父面板也有输入映射,则不会将键击事件传递给嵌套面板。您可以通过注释和取消注释第一次调用getInputMap()。put来观察此行为。有人有解决方案吗?

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 个答案:

答案 0 :(得分:5)