Es gibt eine overloaded form of the asString(...)
method, die eine format string als Argument:
String secondsFormat = "%.1f s" ;
label.textProperty().bind(myobject.secondsProperty().asString(secondsFormat));
Wenn Sie wirklich eine StringConverter
benötigen, können Sie
StringConverter<Integer> deciSecondsConverter = new StringConverter<Integer>() {
@Override
public String toString(Integer deciSeconds) {
return String.format("%.1f s", deciSeconds.doubleValue()/10);
}
@Override
public Integer fromString(String string) {
// not implemented
return null ;
}
};
tun und dann
label.textProperty().bind(Bindings.createStringBinding(
() -> deciSecondsConverter.toString(myobject.getSeconds()),
myobject.secondsProperty()
));
SSCCE :
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class StopwatchTest extends Application {
@Override
public void start(Stage primaryStage) {
IntegerProperty tenthsOfSeconds = new SimpleIntegerProperty();
Label label = new Label();
StringConverter<Integer> deciSecondsConverter = new StringConverter<Integer>() {
@Override
public String toString(Integer deciSeconds) {
return String.format("%.1f s", deciSeconds.doubleValue()/10);
}
@Override
public Integer fromString(String string) {
// not implemented
return null ;
}
};
label.textProperty().bind(Bindings.createStringBinding(() ->
deciSecondsConverter.toString(tenthsOfSeconds.get()),
tenthsOfSeconds));
new AnimationTimer() {
@Override
public void handle(long now) {
tenthsOfSeconds.set((int)System.currentTimeMillis() % 60000/100);
}
}.start();
label.setPadding(new Insets(5, 20, 5, 20));
primaryStage.setScene(new Scene(label, 80, 30));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Das brachte mich auf die richtige Spur, aber da der Wert eine Ganzzahl ist, funktioniert die Formatierung durch Zeichenfolge nicht so, da '.1f' nicht auf int angewendet werden kann. Sie müssen etwas tun wie 'this.label.textProperty(). Bind (Bindings.createFloatBinding (() -> (Gleitkomma) myObject.getSeconds()/10.0f, myObject.secondsProperty()). AsString (secondsFormat)) ; ' – pfried
Wahrscheinlich besser, den Konverter selbst zu reparieren. Siehe Aktualisierung. –