本文介绍了JPanel不响应keylistener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图制作一个JPanel,该面板可以显示您按下每个导航键的次数,但它只显示4个零.
I tried to make a JPanel that would display how many times you press each navigation key, but it is only displaying 4 zeros.
///在keyPressed()方法中,我放置了以下代码来相应地处理按键:
//In the keyPressed() method, I put the following code that handles key presses accordingly:
public void keyPressed(KeyEvent event)
{
if(event.getKeyCode()==KeyEvent.VK_LEFT)
left++;
else if(event.getKeyCode()==KeyEvent.VK_RIGHT)
right++;
else if(event.getKeyCode()==KeyEvent.VK_UP)
up++;
else if(event.getKeyCode()==KeyEvent.VK_DOWN)
down++;
}
//通过paint方法在JPanel上绘制计数
//the paint method to paint the counts over JPanel
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString ( Integer.toString(left), 100, 100 );
g.drawString ( Integer.toString(right), 200, 100 );
g.drawString ( Integer.toString(up), 100, 200 );
g.drawString ( Integer.toString(down), 200, 200 );
}
推荐答案
-
最后在
keyPressed()
方法中调用repaint();
.Call
repaint();
inkeyPressed()
method in the end.在创建后的
main
方法中调用count_keys.setFocusable(true);
Call
count_keys.setFocusable(true);
inmain
method just below its creation由于
JPanel
无法对焦,因此KeyListener
无法正常工作.Because
JPanel
is not focus able henceKeyListener
is not working.这篇关于JPanel不响应keylistener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!