无法显示继承的Node类的实例

时间:2018-04-18 16:51:30

标签: javafx

public void start(Stage primaryStage) {
    Figure figure = new Figure(50,50,100,100,400,400);
    GridPane pane = new GridPane();
    pane.getChildren().addAll(figure);

    Scene scene = new Scene(pane,500,700);

    primaryStage.setTitle("Main");
    primaryStage.setScene(scene);
    primaryStage.show();
}


public class Figure extends Node {
private Circle circle ;
private Line boldLine ;
private Line thinLine ;
private Line prepenLine ;

public Figure(int centerX, int centerY, int startX, int startY, int endX, int endY){
    Circle circle = new Circle(centerX,centerY,10);
    circle.setStroke(Color.GRAY);
    circle.setFill(Color.DARKGRAY);
   prepenLine = new Line(startX,startY,endX,endY);
}

嗨,我正在尝试编写一个类来使用我的自定义节点,如线和圆的组合,但在show()语句中会出现错误。 我无法找到代码的错误。有什么建议吗?

编辑:提供错误以使其更清晰

Exception in thread "JavaFX Application Thread" java.lang.UnsupportedOperationException: Applications should not extend the Node class directly.
    at javafx.graphics/com.sun.javafx.scene.NodeHelper.getHelper(NodeHelper.java:78)
    at javafx.graphics/com.sun.javafx.scene.NodeHelper.transformsChanged(NodeHelper.java:121)
    at javafx.graphics/javafx.scene.Node.nodeResolvedOrientationInvalidated(Node.java:6540)
    at javafx.graphics/javafx.scene.Node.parentResolvedOrientationInvalidated(Node.java:6517)
 etc.

1 个答案:

答案 0 :(得分:1)

根据documentation

  

应用程序不应直接扩展Node类。这样做可能会导致抛出UnsupportedOperationException。

事实上,如果我尝试运行你的代码,那么堆栈跟踪也明确地说明了这一点:

Exception in thread "JavaFX Application Thread" java.lang.UnsupportedOperationException: Applications should not extend the Node class directly.
    at javafx.graphics/com.sun.javafx.scene.NodeHelper.getHelper(NodeHelper.java:78)
    at javafx.graphics/com.sun.javafx.scene.NodeHelper.transformsChanged(NodeHelper.java:121)
    at javafx.graphics/javafx.scene.Node.nodeResolvedOrientationInvalidated(Node.java:6540)
    at javafx.graphics/javafx.scene.Node.parentResolvedOrientationInvalidated(Node.java:6517)
 etc. ...

你的Figure课程实际上并没有做任何事情:它只会创建一些形状(CircleLine s),这些形状是私有的(如此无法访问)。 Node类实际上从未显示过这些形状。没有允许您确定节点绘制方式的公共API。

您可能应该继承Region(或者Pane),并将形状添加为子节点:

public class Figure extends Region {

    private Circle circle ;
    private Line boldLine ;
    private Line thinLine ;
    private Line prepenLine ;

    public Figure(int centerX, int centerY, int startX, int startY, int endX, int endY){
        circle = new Circle(centerX,centerY,10);
        circle.setStroke(Color.GRAY);
        circle.setFill(Color.DARKGRAY);
        prepenLine = new Line(startX,startY,endX,endY);
        getChildren().addAll(circle, prepenLine);
    }

}