0
votes

I have a textfield with a binding to a timestring like this:

timeStringProperty.bind(clock.getTimeString()); 
timeTextField.textProperty().bind(timeStringProperty);    

In Clock.java I have:

public StringBinding getTimeString() {
    return Bindings.createStringBinding(() -> DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM).format(time.get()), time);                             
}

where time comes from a TimeLine.

This works well and the current time is displayed and updated in the timeTextfield.

Now I want to add the ability for the user of my program to determine the format of the time e.g. "hh:mm" or "hh:mm:ss".

How can I bind to a formatString, such that the time display updates with the new format as soon as the formatString value is changed?

1

1 Answers

1
votes

Introduce an ObjectProperty<DateTimeFormatter> to Clock:

public class Clock {

    private final ObjectProperty<DateTimeFormatter> formatter = 
        new SimpleObjectProperty<>(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));

    public ObjectProperty<DateTimeFormatter> formatterProperty() {
        return formatter ;
    }

    public final DateTimeFormatter getFormatter() {
        return formatterProperty().get();
    }

    public final void setFormatter(DateTimeFormatter formatter) {
        formatterProperty().set(formatter);
    }

    // ... other code as before
}

And now update the StringBinding so that it uses the formatter and binds to it:

public StringBinding getTimeString() {
    return Bindings.createStringBinding(() -> getFormatter().format(time.get()), time, formatter);                             
}