KeyListener不会在JPanel上监听

编程入门 行业动态 更新时间:2024-10-28 06:34:00
本文介绍了KeyListener不会在JPanel上监听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是一个非常简单的程序,但是由于某些原因,当我调试它并在keyPressed,keyReleased和keyTyped方法上设置断点时,该程序永远不会在那里停止.

It's a very simple program, but for some reason when I debug it and set breakpoints at the keyPressed, keyReleased and keyTyped method, the program never stops there.

mainKeyListener = new KeyListener() { public void keyPressed(KeyEvent e) { System.out.println("KEY PRESSED"); repaint(); } } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } };

在这里,我将其添加到JPanel中,这是框架的确切大小,也是框架上唯一的对象:

Here I add it to a JPanel, which is the exact size of the frame and the only object on it:

JPanel backgroundPanel = new JPanel(); backgroundPanel.setBounds(0,0, 400, 500); backgroundPanel.addKeyListener(mainKeyListener); backgroundPanel.setFocusable(true); getContentPane().add(backgroundPanel);

推荐答案

您的问题出在重点关注的元素上.我认为您的小组失去了焦点.

Your problem is laying in focused element. I think that your panel lost the focus.

注意: 要触发键盘事件,组件必须具有键盘焦点.对于您的示例,可以通过多种方式解决此问题,您可以使用 KeyboardFocusManager 这样的示例:

Note: To fire keyboard events, a component must have the keyboard focus. It can be solved in many ways for your example you can use KeyboardFocusManager for example like this:

KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); focusManager.addKeyEventDispatcher(new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if(focusManager.getFocusOwner()!=backgroundPanel){ focusManager.redispatchEvent(backgroundPanel,e); return true;} else return false; } });

还要尝试使用键绑定 docs.oracle. com/javase/tutorial/uiswing/misc/keybinding.html

更多推荐

KeyListener不会在JPanel上监听

本文发布于:2023-10-29 10:44:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539479.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:会在   KeyListener   JPanel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!