How to use multiple layers in Piccolo2D?

2019-09-08 16:38发布

I want t have some picture above another one and want to utilize PCamera's addLayer() method.

Is this possible?

The following code throws NullPointerException. What's wrong with it?

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条回答
地球回转人心会变
2楼-- · 2019-09-08 17:29

The problem is that when you set up a new camera it has no associated root. As a result, PCanvas.getRoot() returns null and there an NPE in one of the painting methods. Here is a basic Piccolo2D runtime structure:

enter image description here

Read more in Piccolo2D Patterns.

In your case you're missing a link to PRoot from a PCamera. Here is a simple fix:

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

That results in:

enter image description here

For reference here is a copy from PUtil.createBasicScenegraph() that creates a basic camera.

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;
}
查看更多
登录 后发表回答