当前位置: 代码迷 >> java >> 获取Javafx中DoubleProperty的absolute(int)值
  详细解决方案

获取Javafx中DoubleProperty的absolute(int)值

热度:88   发布时间:2023-07-31 12:10:02.0

我在尝试使用bind在文本/标签中尝试打印DoubleProperty的绝对值时遇到困难...它是一个量表,并且我想在文本/标签中打印针角度值,但是由于它是双精度的属性,它会打印一个双。 这是一个示例:

needleValue = svg1Rotate.angleProperty();
value.textProperty().bind(needleValue.asString());

有趣的是,在Sys.Out中,当我使用NumberFormat时,它就像一种魅力。 像这样:

        System.out.println(NumberFormat.getIntegerInstance().format(needleValue.getValue()));

任何帮助将不胜感激。 提前致谢!!!

您可以创建一个转换器并在绑定中使用它。 在转换器中,您可以创建任何喜欢的表示形式,甚至可以在将值转换为字符串之前计算绝对值。

例:

import java.text.NumberFormat;
import java.text.ParseException;

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        HBox root = new HBox();

        DoubleProperty value = new SimpleDoubleProperty(12.345);

        TextField valueTextField = new TextField();

        Bindings.bindBidirectional(valueTextField.textProperty(), value, new IntegerStringConverter());

        root.getChildren().addAll(valueTextField);

        primaryStage.setScene(new Scene(root, 310, 200));
        primaryStage.show();

    }

    public class IntegerStringConverter extends StringConverter<Number> {

        NumberFormat formatter = NumberFormat.getIntegerInstance();

        @Override
        public String toString(Number value) {

            return formatter.format(value);

        }

        @Override
        public Number fromString(String text) {

            try {

                return formatter.parse(text);

            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

        }

    }

    public static void main(String[] args) {
        launch(args);
    }
}
  相关解决方案