我试图让图像随机移动,但由于某种原因它不起作用。图像出现在面板中,但没有移动。我为此使用了两个类:一个主类和一个子类。这是我的子类的代码。
public Image()
{
randomPosition();
try {
image = ImageIO.read(new File("image.png"));
} catch (IOException e) {}
}
public void paint(Graphics g)
{
g.drawImage(image, x, y, this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void move()
{
x += dx;
y += dy;
if (x >= 550) {
x = 550;
randomDirection();
}
if (x <= 1) {
x = 1;
randomDirection();
}
if (y >= 350) {
y = 350;
randomDirection();
}
if (y <= 1) {
y = 1;
randomDirection();
}
}
public void randomDirection() {
double speed = 2.0;
double direction = Math.random()*2*Math.PI;
dx = (int) (speed * Math.cos(direction));
dy = (int) (speed * Math.sin(direction));
}
public void randomPosition()
{
x = LEFT_WALL + (int) (Math.random() * (RIGHT_WALL - LEFT_WALL));
y = UP_WALL + (int) (Math.random() * (DOWN_WALL - UP_WALL));
}
public void run()
{
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (true)
{
move();
repaint();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;
if (sleep > 2)
{
sleep = 1;
}
try
{
Thread.sleep(sleep);
}
catch (InterruptedException e)
{
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
}
这是我启动线程的主类:
public void addImage(){
Image I = new Image();
x = panel.getGraphics();
I.paint(x);
Thread thr=new Thread(I);
thr.start();
}
最佳答案
paint()
应该是
像这样:
public void paintComponent(Graphics g) {
super.paintComponent(g);
...
}
切勿直接调用
paint()/paintComponent()
。而是调用repaint()
,这会将其添加到事件队列中。图形对象由swing传递。我不确定 g.dispose() 是否必要,并且可能会导致问题。
- 检查您的绘画所在的面板尺寸是否正确 - 调试此问题的快速方法是
panel.setBorder(BorderFactory.createLineBorder(Color.RED));
- 考虑使用 javax.swing.Timer 而不是线程。这不是问题的原因,但会更干净。
关于java - 尝试使图像随机移动但它没有移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28997654/