Alex
Alex

Reputation: 197

Bind model to a custom control using fxml

I have to custom controls, parent and child. And want to assign a part of the model, that is not a simple string that is available in the parent to a child using fxml. Is it possible?

Parent

public class ParentControl extends VBox {

  public LocalDate getDate() {
    return LocalDate.now();
  }
  
  public ParentControl() {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(
        "/parent.fxml"));
    fxmlLoader.setRoot(this);
    fxmlLoader.setController(this);
....

Custom control

public class CustomControl extends VBox {

  @Getter
  @Setter
  LocalDate date;

parent.fxml

<?xml version="1.0" encoding="UTF-8"?>
<?import com.example.javafx.CustomControl?>
<?import javafx.scene.layout.VBox?>
<fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml">
    <CustomControl date="${date}"/>
</fx:root>

Upvotes: 0

Views: 107

Answers (1)

Puce
Puce

Reputation: 38132

  @Getter
  @Setter
  LocalDate date;

I guess you're using Lombok there? Lombok currently does not support JavaFX (there is an open feature request) and once it does I guess it will use different annotations.

For property binding you'll need a JavaFX property:

private final ObjectProperty<LocalDate> date= new SimpleObjectProperty<>(this, "date", null);

[...]

public final LocalDate getDate() {
    return dateProperty().get();
}

public final void setDate(LocalDate date) {
    dateProperty().set(date);
}

public ObjectProperty<LocalDate> dateProperty() {
    return date;
}

The date property of the ParentControl you'll need to change to an ObservableValue. The question is what is the expected behaviour with LocalDate.now? Do you expect that CustomControl.date will always have the current time? Or the time when it was initialzed?

Upvotes: 1

Related Questions