本文介绍了JavaFX接受特定对象类型的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaFX中是否有一种方法可以创建一个扩展 Group 的类,并将其限制为仅接受 Shape 对象作为孩子?

Is there a way in JavaFX to make a class that extends Group and limit it to accepting only Shape objects as children?

推荐答案

考虑创建一个包装类而不是子类。

Consider creating a wrapper class instead of a subclass. Something along the lines of

public class ShapeGroup {

    private final Group group = new Group() ;

    public void addShape(Shape s) {
        group.getChildren().add(s);
    }

    public void removeShape(Shape s) {
        group.getChildren().remove(s);
    }

    // other methods you want to expose, implemented similarly...

    public Parent asParent() {
        return group ;
    }
}

现在你可以按如下方式使用:

And now you can use this as follows:

ShapeGroup shapeGroup = new ShapeGroup();
shapeGroup.addShape(new Circle(50, 50, 20));
shapeGroup.addShape(new Rectangle(20, 20, 30, 30));
// ...
Scene scene = new Scene(shapeGroup.asParent());
// etc..

这篇关于JavaFX接受特定对象类型的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:55