【发布时间】:2013-05-22 01:05:52
【问题描述】:
我正在模拟 人 在连接节点图上行走。为了直观地显示它,我使用了画布对象。我首先通过它的节点和它们之间的链接来渲染图形,然后我开始绘制 person,它由一个在图形中移动的小方块表示。
我的问题是,在我绘制地图(或图表)后,人的动画会删除标签,有时还会删除图表的线条。我知道这是因为我渲染了人的动作
在包含地图的同一画布上(并且由于 clearRect() 方法调用)。
如何避免清除图表?起初我查看了JLayeredPane,但画布重叠并且在最上面的画布上没有透明度(没有透明的人)。我想到的第二个选项是在绘制人之前复制该区域,然后在人移动时恢复该区域,但我不确定如何实现这一点,因此我没有使用过swing 或awt 这么多,我认为这可能是一个常见问题。
我附上了一张图片来显示我的问题以及我为每个人
的渲染代码public class Person extends Thread {
public Person(String name, Spot location, World world, Graphics g) {
this.name= name;
this.location= location;
this.world= world;
this.g= g;
}
private void move() {
Set<Link> links= world.getLinksFrom(location.getId());
Link route= CollectionUtil.getRandomElement(links);
Spot destination= route.getOriginX() == location.getX() &&
route.getOriginY() == location.getY() ?
route.getTheTarget(): route.getTheOrigin();
try {
double deltaX= (destination.getX() - location.getX()) / route.distance();
double deltaY= (destination.getY() - location.getY()) / route.distance();
double w2= (PERSON_WIDTH / 2);
for(double i=location.getX(), j=location.getY(), d= route.distance();
d > 5;
i+=deltaX, j+= deltaY,
d=Point2D.distance(i, j, destination.getX(), destination.getY())) {
g.clearRect((int)(i - w2 - deltaX), (int)(j - w2 - deltaY),
PERSON_WIDTH, PERSON_WIDTH);
g.drawRect((int)(i-w2), (int)(j-w2),
PERSON_WIDTH-1, PERSON_WIDTH-1);
Thread.sleep(50);
}
this.location= destination;
// Stay ath the new location for a while
Thread.sleep(new Random(System.currentTimeMillis()).nextInt(Person.MAX_SPOT_MILLIS));
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
@Override
public void run() {
while(!isInterrupted()) {
this.move();
}
}
}
【问题讨论】:
-
如需尽快获得更好的帮助,请发帖SSCCE。
-
没有足够的信息继续下去,但是,看起来您存储了对图形对象的引用,可能是通过使用 getGraphics。这不是一个好主意。 getGraohics 返回的图形上下文可以为空,并在重绘之间更改。您似乎也在事件 Dispathing 线程之外更新 UI。这也是一个坏主意,因为您实际上无法控制重绘发生的时间,并且可能会产生绘画伪影。更多详情请关注Custom Painting
-
您对您假设的一切都是正确的(
getGraphics参考,每个人都是Thread),感谢您提供的链接我会看看我是否可以设置一个SSCCE 作为@AndreThompson 点出来。 -
使用 JLayer/GlassPane 在上面绘画
-
不要通过 Thread.sleep(int) 阻止 EDT,也不要阻止 OpenGL/CL
标签: java swing user-interface awt graphics2d