JLabel的KeyListener对我不起作用 [英] KeyListener for JLabel don't work for me
问题描述
当我按下向上或向下箭头时,我的代码出现问题。
这是我的代码,对不起我的英文。
这是Racket 1的一部分,Racket 2 id的部分类似。
I have a problem with my code when I pressed on the up or down arrow nothing happen. Here's my code and sorry for my english. This is the part for the Racket 1, the part for the Racket 2 id similar.
//--->Racket 1 :
Racket1.addKeyListener(this);
Racket1.setBounds(50, 200, 16, 100); //<----- setBounds (Placer position du JLabel x,y + taille de la plateforme x,y)
Racket1.setBackground(Color.white);
Racket1.setOpaque(true);
Racket1.setFocusable(true); //<----- Permet d'utiliser KeyListener Pour un JLabel
Racket1.requestFocus();
这是keyListener的一部分:
And this is the part of the keyListener :
public void keyTyped (KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
Racket1.setLocation(Racket1.getX(), Racket1.getY() +20);
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
Racket1.setLocation(Racket1.getX(), Racket1.getY() -20);
}
else if (e.getKeyCode() == 'z') {
Racket2.setLocation(Racket2.getX(), Racket2.getY() +20);
}
else if (e.getKeyCode() == 's') {
Racket2.setLocation(Racket2.getX(), Racket2.getY() -20);
}
}
public void keyReleased(KeyEvent e) {
推荐答案
不要使用KeyListener。一次只有一个组件可以拥有焦点,因此您只能移动其中一个球拍。
Don't use a KeyListener. Only one component can have focus at a time, so you will only ever be able to move one of the rackets.
相反,您应该使用键绑定
。 键绑定
用于将 Action
绑定到 KeyStroke
并且该组件不需要具有焦点。
Instead you should be using KeyBindings
. Key Bindings
are used to bind an Action
to a KeyStroke
and the component doesn't need to have focus.
查看使用键盘进行运动以获取更多信息。 KeyboardAnimation.java
甚至有一个使用两个标签的例子。
Check out Motion Using the Keyboard for more information. The KeyboardAnimation.java
even has an example that uses two labels.
这篇关于JLabel的KeyListener对我不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!