在嵌套面板中聆听按键 [英] Listening for key strokes in a nested panel

查看:103
本文介绍了在嵌套面板中聆听按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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秒登录
发送“验证码”获取 | 15天全站免登陆