當我運行該程序時,一切正常,這一切工作和東西,但圖形不斷閃爍。我是新手做這樣的事情,我不知道如何解決這個問題。圖形閃爍
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class MovementTest extends Frame implements Runnable, MouseMotionListener, KeyListener {
private static Thread thread;
private int mouseX, mouseY;
private boolean movingRight;
private boolean movingLeft;
private boolean movingUp;
private boolean movingDown;
private Rectangle player = new Rectangle(50, 50, 100, 100);
private Rectangle wallOne = new Rectangle(400, 50, 100, 100);
public MovementTest() {
setSize(800, 600);
setVisible(true);
addKeyListener(this);
addMouseMotionListener(this);
}
public static void main(String[] args) {
thread = new Thread(new MovementTest());
thread.start();
}
@Override
public void run() {
try {
while(true) {
if(player.intersects(wallOne)) {
thread.stop();
break;
}
if(movingRight) {
player.x++;
} else if(movingLeft) {
player.x--;
}
if(movingUp) {
player.y--;
} else if(movingDown) {
player.y++;
}
paint(getGraphics());
Thread.sleep(5);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_D)
movingRight = true;
if (key == KeyEvent.VK_A)
movingLeft = true;
if (key == KeyEvent.VK_W)
movingUp = true;
if (key == KeyEvent.VK_S)
movingDown = true;
}
@Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_D)
movingRight = false;
if (key == KeyEvent.VK_A)
movingLeft = false;
if (key == KeyEvent.VK_W)
movingUp = false;
if (key == KeyEvent.VK_S)
movingDown = false;
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void paint(Graphics g) {
g.drawString("x: " + mouseX + " y: " + mouseY, 5, 35);
g.drawRect(player.x, player.y, 100, 100);
g.drawRect(wallOne.x, wallOne.y, 100, 100);
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
}
我沒有得到最後一句話。 –
最後一句由Stack Overflow生成。我不確定他在帖子中是如何結束的,它應該只是一個信息。 – corsiKa
你有沒有使用Swing的原因?你不應該直接調用'paint()'(改爲調用'repaint()')。編碼你自己的更新循環是要求讓自己瘋狂;查看'Events' /'Listeners'。嘗試[教程](http://download.oracle.com/javase/tutorial/uiswing/index.html)可能會對您有所幫助。 –