JavaFX 文本域绑定
JavaFX textfield binding
我有一个绑定到时间字符串的文本字段,如下所示:
timeStringProperty.bind(clock.getTimeString());
timeTextField.textProperty().bind(timeStringProperty);
在 Clock.java 我有:
public StringBinding getTimeString() {
return Bindings.createStringBinding(() -> DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM).format(time.get()), time);
}
时间来自时间线。
这很好用,当前时间在时间文本字段中显示和更新。
现在我想为我的程序的用户添加确定时间格式的功能,例如"hh:mm" 或 "hh:mm:ss".
如何绑定到 formatString,以便在更改 formatString 值后立即使用新格式更新时间显示?
向Clock
介绍一个ObjectProperty<DateTimeFormatter>
:
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
}
现在更新 StringBinding
以便它使用 formatter
并绑定到它:
public StringBinding getTimeString() {
return Bindings.createStringBinding(() -> getFormatter().format(time.get()), time, formatter);
}
我有一个绑定到时间字符串的文本字段,如下所示:
timeStringProperty.bind(clock.getTimeString());
timeTextField.textProperty().bind(timeStringProperty);
在 Clock.java 我有:
public StringBinding getTimeString() {
return Bindings.createStringBinding(() -> DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM).format(time.get()), time);
}
时间来自时间线。
这很好用,当前时间在时间文本字段中显示和更新。
现在我想为我的程序的用户添加确定时间格式的功能,例如"hh:mm" 或 "hh:mm:ss".
如何绑定到 formatString,以便在更改 formatString 值后立即使用新格式更新时间显示?
向Clock
介绍一个ObjectProperty<DateTimeFormatter>
:
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
}
现在更新 StringBinding
以便它使用 formatter
并绑定到它:
public StringBinding getTimeString() {
return Bindings.createStringBinding(() -> getFormatter().format(time.get()), time, formatter);
}