在嵌套面板中聆听按键 [英] Listening for key strokes in a nested panel
问题描述
在下面的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);
}
});
}
}
推荐答案
-
请参阅Oracle教程如何使用键绑定
您错过了将重点放在JPanel panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(...)
you miss there set focus to JPanel panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(...)
这篇关于在嵌套面板中聆听按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!