3

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

3
  • 1
    Override the method that accepts Nodes to Shapes
    – Steven
    Jan 4, 2016 at 3:12
  • 2
    @Strven: You cannot override a method with a implementation that uses different parameter types (except for type erasure) and even if you could you shouldn't, since it violates the Liskov substitution principle.
    – fabian
    Jan 4, 2016 at 10:01
  • 1
    Thanks Steve. @Fabian, indeed I could not override the getchildren().add(...) method. Thanks for link. I'll read up.
    – melkhaldi
    Jan 4, 2016 at 13:57

1 Answer 1

5

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..
3
  • 1
    Thanks James_D. Yes, that is the solution I was thinking about, but was hoping for another way to avoid writing wrappers for all methods I could possibly use from Group :/ . Having started using type parameters recently, I am not sure why Java does not have this for Groups. I might be wrong, but it sounds like a good idea...
    – melkhaldi
    Jan 4, 2016 at 13:54
  • 1
    Too many type parameters would clutter the API and make it too complex. There are very few methods in Group that are not inherited from Parent, and Parent only exposes the child nodes as an unmodifiable list, so there isn't much you need to write for a wrapper in this case.
    – James_D
    Jan 4, 2016 at 13:57
  • 1
    Will give it a try. Thanks!
    – melkhaldi
    Jan 4, 2016 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.