如何在Piccolo2D中使用多个图层?

时间:2013-12-25 13:16:50

标签: java graphics piccolo

我希望在另一张图片之上有一些图片,并希望使用PCameraaddLayer()方法。

这可能吗?

以下代码抛出NullPointerException。怎么了?

package test.piccolo;

import java.awt.Color;

import edu.umd.cs.piccolo.PCamera;
import edu.umd.cs.piccolo.PLayer;
import edu.umd.cs.piccolo.nodes.PPath;
import edu.umd.cs.piccolox.PFrame;

public class Try_Cameras_01 {
    @SuppressWarnings("serial")
    public static void main(String[] args) {
        new PFrame() {



            private PLayer layer1 = new PLayer();

            private PLayer layer2 = new PLayer();

            private PLayer layer3 = new PLayer();

            private PCamera camera = new PCamera();
            {
                camera.addLayer(layer1);
                camera.addLayer(layer2);
                camera.addLayer(layer3);
            }


            @Override
            public void initialize() {

                getCanvas().setCamera(camera);

                PPath redRectangle = PPath.createRectangle(0, 0, 100, 100);
                redRectangle.setStrokePaint(Color.black);
                redRectangle.setPaint(Color.red);

                PPath greenRectangle = PPath.createRectangle(20, 20, 100, 100);
                greenRectangle.setStrokePaint(Color.black);
                greenRectangle.setPaint(Color.green);

                PPath blueRectangle = PPath.createRectangle(40, 40, 100, 100);
                blueRectangle.setStrokePaint(Color.black);
                blueRectangle.setPaint(Color.blue);

                layer1.addChild(redRectangle);
                layer2.addChild(greenRectangle);
                layer3.addChild(blueRectangle);


            }
        };
    }
}

1 个答案:

答案 0 :(得分:1)

问题在于,当您设置新相机时,它没有关联的根。因此,PCanvas.getRoot()会返回null,并在其中一种绘画方法中返回NPE。这是一个基本的Piccolo2D运行时结构:

enter image description here

Piccolo2D Patterns中阅读更多内容。

在您的情况下,您错过了PRootPCamera的链接。这是一个简单的修复:

private PCamera camera = new PCamera(); {
    PRoot root = new PRoot();
    root.addChild(camera);
    camera.addLayer(layer1);
    camera.addLayer(layer2);
    camera.addLayer(layer3);
}

结果是:

enter image description here

此处参考是PUtil.createBasicScenegraph()创建基本相机的副本。

public static PCamera createBasicScenegraph() {
    final PRoot root = new PRoot();
    final PLayer layer = new PLayer();
    final PCamera camera = new PCamera();

    root.addChild(camera);
    root.addChild(layer);
    camera.addLayer(layer);

    return camera;
}