【发布时间】:2018-11-25 18:08:45
【问题描述】:
作为学校项目的一部分,我们必须使用 Applets 创建一个小游戏。我现在正在做一些测试,但有一件事我不太明白: 我想在我的 Applet 屏幕上同时在我的屏幕上飞行多个对象。动画效果是通过绘制对象,删除它然后在一段时间后移动它来创建的。
这是我的代码: 机器人世界级 封装核心;
import items.Obstacle;
import java.applet.Applet;
import java.awt.*;
import java.util.ArrayList;
public class Roboterwelt extends Applet {
private ArrayList<Obstacle> obstacles = new ArrayList<>();
@Override
public void init() {
setSize(600, 600);
Graphics g = getGraphics();
g.setColor(Color.BLACK);
for(int x = 0; x < 5; x++) {
Obstacle h = new Obstacle((x+1)*100, 100, g, this);
obstacles.add(h);
Thread t = new Thread(h);
t.start();
}
}
@Override
public void paint(Graphics g) {
for(Obstacle o : obstacles) {
o.draw();
}
}
}
障碍类 包装物品;
import java.applet.Applet;
import java.awt.*;
public class Obstacle implements Runnable {
private int x;
private int y;
private Graphics g;
public Hindernis(int x, int y, Graphics g) {
this.x = x;
this.y = y;
this.g = g;
}
public void draw() {
g.drawOval(x, y, 50, 50); //Draw obstacle
}
//Deleting the obstacle by covering it with a white circle
public void delete() {
g.setColor(Color.WHITE); //Change the color to white
g.fillOval(x-5,y-5,60,60); //Making it a bit bigger than the obstacle to fully cover it
g.setColor(Color.BLACK); //Reset the color to black
}
@Override
public void run() {
try {
while(y < 600) {
delete();
y += 10;
draw();
Thread.sleep(1000);
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
问题是我更改图形对象的颜色以覆盖白色圆圈的部分。当我有多个线程运行以表示屏幕上的多个障碍并且同时发生重绘和删除时,线程在将颜色更改为白色后被中断,并使用 Graphics 对象绘制一个填充的椭圆,该对象的颜色被另一个线程设置为黑色将 delete() 方法运行到最后。
如何强制程序在颜色变为白色和绘制填充的椭圆形之间不中断 delete() 方法?
【问题讨论】:
-
1.不要使用
getGraphics,这不是自定义绘画的方式; 2.不要覆盖顶级容器的paint,在你的情况下,Applet不是双缓冲的,所以你最终会闪烁; 3. 您不需要多个线程,您只需要一个(更多线程!= 完成更多工作); -
@MadProgrammer 那我应该如何同时移动多个障碍物?
-
使用单线程,循环实体列表。使用
Thread.sleep控制帧率 -
但它们不会同时移动,对吧?当我得到正确的时机时,它们看起来就像它们一样。
-
“更新”和您绘画的时间之间的时间意味着它们似乎同时移动 - 假设您正在正确执行绘画