我正在尝试使图像随机移动,但由于某种原因它不起作用。图像显示在面板中但它没有移动。我正在使用两类:主类和子类。这是我的子类的代码。
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();
}
答案 0 :(得分:1)
paint()
应像这样:
public void paintComponent(Graphics g) {
super.paintComponent(g);
...
}
切勿直接致电paint()/paintComponent()
。而是调用repaint()
,这会将其添加到事件队列中。图形对象通过swing传递。
我不确定g.dispose()是否必要,可能会导致问题。
panel.setBorder(BorderFactory.createLineBorder(Color.RED));