元素不显示在窗格内的窗格上

Avi*_*der 2 java user-interface javafx

我正在 JavaFX 中编写矢量画布(矢量图形,画布上仅显示形状):好吧,这样您就可以四处移动并放大它。

由于翻译时节点左上角的位置发生了变化,并且不再响应点击,因此我决定在画布本身内部创建一个面板,在上面显示所有内容。

里面VectorCanvas有一个VectorCanvasContent.
线条被添加到VectorCanvasContent,但由于某种原因它们不可见(尽管它们在那里,我添加了一个侦听器,当您单击它们并检查时,该侦听器会输出“!!!”)。
如果我在画布上画线,那么它们是可见的。

问题是什么?

import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;

import java.util.function.Consumer;

public class VectorCanvas extends Pane {

    public class VectorCanvasContent extends Pane {
        public static final Consumer<VectorCanvas> DEFAULT_DRAWER = canvas -> {
            Line[] lines = {
                    new Line(0, 0, canvas.getWidth(), 0),
                    new Line(canvas.getWidth(), 0, canvas.getWidth(), canvas.getHeight()),
                    new Line(canvas.getWidth(), canvas.getHeight(), 0, canvas.getHeight()),
                    new Line(0, canvas.getHeight(), 0, 0),
                    new Line(0, 0, canvas.getWidth(), canvas.getHeight()),
                    new Line(0, canvas.getHeight(), canvas.getWidth(), 0)
            };
            for (Line line : lines) {
                line.setStrokeWidth(30);
                line.setStroke(Color.RED);
                line.setFill(Color.RED);
                line.setOnMouseClicked(mouseEvent -> System.out.println("!!!"));
            }
            canvas.drawAll(lines);
        };
    }

    private final Consumer<VectorCanvas> drawer;

    public final VectorCanvasContent content = new VectorCanvasContent();

    public VectorCanvas() {
        this(VectorCanvasContent.DEFAULT_DRAWER);
    }

    public VectorCanvas(Consumer<VectorCanvas> drawer) {
        this.drawer = drawer;
        getRealChildren().add(content);
        draw();
    }

    public void clear() {
        getChildren().clear();
    }

    public void draw() {
        if (drawer != null)
            drawer.accept(this);
    }

    public void redraw() {
        clear();
        draw();
    }

    @Override
    public ObservableList<Node> getChildren() {
        return content.getChildren();
    }

    @Override
    public ObservableList<Node> getChildrenUnmodifiable() {
        return content.getChildrenUnmodifiable();
    }

    private ObservableList<Node> getRealChildren() {
        return super.getChildren();
    }

    private ObservableList<Node> getRealChildrenUnmodifiable() {
        return super.getChildrenUnmodifiable();
    }

    public void draw(Shape shape) {
        getChildren().add(shape);
    }

    public void drawAll(Shape... shapes) {
        getChildren().addAll(shapes);
    }
}
Run Code Online (Sandbox Code Playgroud)

jew*_*sea 5

您不应该覆盖getChildren()并getChildrenUnmodifiable()返回不同节点(尤其是包含的节点)的子节点。

这可能会混淆并破坏 JavaFX 布局系统,因为这对它来说是非常意想不到的。