SimpleEllipseExample 只是在 Piccolo2D 中不起作用



下面的短笛示例实际上应该做什么?我什么都不画。而绘画方法从未调用过:

package test.piccolo;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.nodes.PText;
import edu.umd.cs.piccolo.util.PPaintContext;
import edu.umd.cs.piccolox.PFrame;
public class SimpleEllipseNode extends PNode {
    private Ellipse2D ellipse;
    // This nodes uses an internal Ellipse2D to define its shape.
    public Ellipse2D getEllipse() {
        if (ellipse == null)
            ellipse = new Ellipse2D.Double();
        return ellipse;
    }
    // This method is important to override so that the geometry of
    // the ellipse stays consistent with the bounds geometry.
    public boolean setBounds(double x, double y, double width, double height) {
        if (super.setBounds(x, y, width, height)) {
            ellipse.setFrame(x, y, width, height);
            return true;
        }
        return false;
    }
    // Non rectangular subclasses need to override this method so
    // that they will be picked correctly and will receive the
    // correct mouse events.
    public boolean intersects(Rectangle2D aBounds) {
        return getEllipse().intersects(aBounds);
    }
    // Nodes that override the visual representation of their super
    // class need to override a paint method.
    public void paint(PPaintContext aPaintContext) {
        Graphics2D g2 = aPaintContext.getGraphics();
        g2.setPaint(getPaint());
        g2.fill(getEllipse());
    }
    public static void main(String[] args) {
        PFrame frame = new PFrame() {
            @Override
            public void initialize() {
                PNode aNode = new SimpleEllipseNode();
                //PNode aNode = new PText("Hello World!");
                // Add the node to the canvas layer so that it
                // will be displayed on the screen.
                getCanvas().getLayer().addChild(aNode);
            }
        };
    }
}

椭圆没有被绘制,可能是因为SimpleEllipseNode的边界是空的。将这些行添加到initialize()

aNode.setPaint(Color.RED);
aNode.setBounds(0, 0, 100, 100);

它应该画一个红色的椭圆。setBounds()有一个 NPE,因为ellipse尚未初始化。这可以通过在setBounds()中添加getEllipse();作为第一行来修复。

不确定覆盖paint()setBounds()背后的原因是什么,因为通常您可以通过使用组合节点轻松逃脱。例如:

import java.awt.Color;
import edu.umd.cs.piccolo.nodes.PPath;
import edu.umd.cs.piccolox.PFrame;
public class SimpleEllipseNode {
    public static void main(final String[] args) {
        PFrame frame = new PFrame() {
            @Override
            public void initialize() {
                final PPath circle = PPath.createEllipse(0, 0, 100, 100);
                circle.setPaint(Color.RED);
                getCanvas().getLayer().addChild(circle);
            }
        };
    }
}

相关内容

  • 没有找到相关文章

最新更新