我试图让我的迷你游戏(绘画)检测键盘点击,即,向上箭头键继续椭圆形线。问题是,当我运行程序并输入向上箭头键,或向下或向左或向右键时,程序不会执行任何操作。请帮忙。
以下是所有代码:
package MiniGame;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class GameTest extends JFrame{
int x;
int y;
//This class detects the keys pressed.
public class Actionlistener extends KeyAdapter{
public void KeyPressed(KeyEvent ke){
int Listen = ke.getKeyCode();
if(Listen == ke.VK_UP ) {y--;}
if(Listen == ke.VK_LEFT) {x--;}
if(Listen == ke.VK_DOWN) {y++;}
if(Listen == ke.VK_RIGHT){x++;}
}
public void KeyReleased() {
//There's no code here yet.
}
}
//The constructor that initialises some components.
public GameTest() {
addKeyListener(new Actionlistener());
setTitle("Game Test");
setSize(750, 750);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
x = 150;
y = 150;
} //Paint method.
public void paint(Graphics g) {
g.fillOval(x, y, 20, 20);
repaint();
}
//Creating an object
public static void main(String[] args){
new GameTest();
}
}
答案 0 :(得分:1)
不要使用KeyListener! Swing旨在与Key Bindings
一起使用。
有关为什么不应使用KeyListener和Key Bindings
的工作示例来帮助您入门的更多信息,请参阅Motion Using the Keyboard。