这是一个非常简单的程序,但是由于某些原因,当我调试它并在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上监听
发布评论