sara
sara

Reputation: 3589

JavaFX - Defining the default property

I have created a custom control that extends Region using the fx:root element. My problem is that when I try to load it, I get a LoadException, claiming that I need to define a DefaultProperty. From what I can tell, Region doesn't expose getChildren() as public so as to let developers decide if clients can add stuff freely or not.

My question is how do I actually define children as the default property? I tried reading the docs but they only say what the annotation is for, not how it's used. I haven't been able to find any examples either. Every time I try to annotate a field or method with @DefaultProperty, I just get the compile error The annotation @DefaultProperty is disallowed for this location.

Upvotes: 0

Views: 3510

Answers (1)

James_D
James_D

Reputation: 209330

The @DefaultProperty annotation is a class-level annotation (@Target(value=TYPE) in the documentation) with a required value attribute specifying the name of the property.

So the following would work:

@DefaultProperty("children")
public class SpecialRegion extends Region {

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

Note that if you don't make getChildren() public, then the FXMLLoader won't be able to access it in a way that enables it to populate it. So even with the @DefaultProperty annotation, I don't think you can make this work without making the getChildren() method public, as above. At this point, you may as well subclass Pane instead of Region: the only differences between Pane and Region are the public getChildren() method and the DefaultProperty.

Upvotes: 3

Related Questions