我在寫一個類來圍繞屏幕移動一個圓,但主要問題是布爾變量不會更改爲true,儘管我嘗試將它們更改爲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) {
}
}
使用'KeyListener'上的鍵綁定來克服'KeyListener'的所有相關問題。請參閱[如何使用關鍵綁定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer
哦,除非您使用'BufferStrategy',否則我還會推薦使用AWT庫上的Swing庫... – MadProgrammer