用Java在画布上画东西

用Java在画布上画东西,java,canvas,draw,Java,Canvas,Draw,我有一个实体对象列表,我想在画布上使用Graphics2D对象绘制所有实体对象,但如果某些对象位于同一位置,则必须在其他对象上绘制,我有一个解决方案如下: for(Entity e : cloneEntities) if (e instanceof Dirty) e.render(g); for(Entity e : cloneEntities) if (e instanceof Box) e.render(g); for(Entity e

我有一个实体对象列表,我想在画布上使用Graphics2D对象绘制所有实体对象,但如果某些对象位于同一位置,则必须在其他对象上绘制,我有一个解决方案如下:

    for(Entity e : cloneEntities)
        if (e instanceof Dirty) e.render(g);
    for(Entity e : cloneEntities)
        if (e instanceof Box) e.render(g);
    for(Entity e : cloneEntities)
        if (e instanceof RunObstacle) e.render(g);

但它看起来是巨大的。对于这种情况,还有其他解决方案吗?提前谢谢

您可以按类型对克隆性进行排序(您可能需要自定义比较器来指定顺序),然后按顺序呈现它们。与@patrick hainge的答案类似,您可以在
实体中添加一个名为
z-index
int
类型的字段,该字段在
实体的构造函数中设置。因此,您的子构造函数需要向其发送一个值

然后,您只需对
cloneeties
列表进行排序,然后对每个列表调用render,如下所示:

clonedEntities.stream().sort((a,b)->a.getZindex()-b.getZindex()).forEach((a)->a.render(g));
注意


只有当
cloneenties
声明为
列表而不是
集合时,这才起作用
cloneenties

可能最好的解决方案是为前面、中间和背景创建一些缓冲区图像:

BufferedImage dirties = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Buffered Image boxes = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
BufferedImage obstacles = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

for(Entity e : cloneEntities){
    if (e instanceof Dirty) e.render(dirties.getGraphics());
    if (e instanceof Box) e.render(boxes.getGraphics());
    if (e instanceof RunObstacle) e.render(obstacles.getGraphics());
}
//And then render all Layers
 g.drawImage(dirties, 0, 0, width, height, null);
 g.drawImage(boxes, 0, 0, width, height, null);
 g.drawImage(obstacles, 0, 0, width, height, null);

这个解决方案是由。

也可以将
z-index
作为常量(因此
公共静态final
),这样我们就可以直接处理它们,而不必调用
getZindex()
一整段时间。这可能是一个边际性能提升,但考虑到您可能正在用Java编写游戏,这一点值得记住。我以前在游戏编程(textureId)的其他方面也尝试过,但我总是遇到同样的问题。使其为静态将删除对象的上下文,因此,如果不在父对象上使用
.getClass()
,则无法从父对象调用静态方法。不完全确定细节,但我相信它使用了反射,因此性能增益可能会抵消,因为反射很重。我没有想到这一点,谢谢。让我们的超类实现
compariable
并重写
comparieto
方法来直接处理另一个
实体的
z-index
字段(假设我们将z-index的访问权限设置为
protected
),以及对“cloneEntities”对象的解释,这也是一个问题,当我访问实体列表来呈现其中的每个对象时,我遇到了这个问题:java.util.ArrayList$Itr.CheckForComodition(ArrayList.java:901)java.util.ArrayList$Itr.next(ArrayList.java:851)Main.Floor.render(Floor.java:54)Main.Game.render(Game.java:102)的线程“thread-2”java.util.ConcurrentModificationException中的异常在Main.Game.run(Game.java:159)和java.lang.Thread.run(Thread.java:745)中,无论您是否有意,都似乎在运行多个线程。这个问题的解决办法超出了这个问题的范围。在“并发修改异常Java列表”上进行良好搜索,您将找到大量帮助:)