我正在编写一个类来在屏幕上移动一个圆圈,但主要问题是布尔变量没有更改为true,尽管我试图使它们更改为true。我不知道我做错了什么。请帮忙。谢谢。
public class Restart extends Panel implements KeyListener {
static final int left = 37;
static final int right = 39;
static final int down = 40;
static final int up = 38;
static boolean leftPress = false;
static boolean rightPress = false;
static boolean upPress = false;
static boolean downPress = false;
static int x1 = 0;
static int y1 = 0;
Restart(int width, int length, int minusBy) {
super(width, length, minusBy);
}
public static void main(String args[]) throws InterruptedException {
Restart panel = new Restart(500, 500, 9);
JFrame frame = new JFrame("Fishy");
frame.add(panel);
Frame.showFrame(frame);
while (true) {
if (upPress) {
y1--;
}
if (downPress) {
y1++;
}
if (leftPress) {
x1--;
}
if (rightPress) {
x1++;
}
Thread.sleep(1);
frame.repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(x1, y1, 50, 50);
}
@Override
public void keyPressed(KeyEvent e) {
if (up == e.getKeyCode()) {
upPress = true;
}
if (down == e.getKeyCode()) {
downPress = true;
}
if (left == e.getKeyCode()) {
leftPress = true;
}
if (right == e.getKeyCode()) {
rightPress = true;
}
}
@Override
public void keyReleased(KeyEvent e) {
if (up == e.getKeyCode()) {
upPress = false;
}
if (down == e.getKeyCode()) {
downPress = false;
}
if (left == e.getKeyCode()) {
leftPress = false;
}
if (right == e.getKeyCode()) {
rightPress = false;
}
}
/* NOT USING */
@Override
public void keyTyped(KeyEvent e) {
}
}
从不将密钥侦听器添加到任何组件。因此,您不会获得任何输入。通过调用 someComponent.addKeyListener(this)
将重新启动作为密钥侦听器添加到某些Component
(JPanel
和其他一些可能需要使用 setFocusable(true)
使某些可聚焦)。我建议您将侦听器添加到Restart
实例本身。