JavaFX中是否有一种方法可以创建一个扩展Group
的类并将其限制为只接受Shape
个对象作为子级?
答案 0 :(得分:4)
考虑创建一个包装类而不是子类。
的内容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 ;
}
}
现在你可以按如下方式使用它:
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..