How to pass number to TextField JavaFX?

后端 未结 3 754
独厮守ぢ
独厮守ぢ 2021-01-23 18:20

I am working on simple calculator, where users input two numbers in TextField and the result is displayed in result TextField. I used Double.pars

3条回答
  •  没有蜡笔的小新
    2021-01-23 19:05

    setText expects a String as parameter. You need to convert the result to a String, e.g. by using Double.toString.

    However in this case I recommend adding a TextFormatter to the TextField which allows you to assign/input values of a type different to String using a TextField:

    TextField summand1 = new TextField();
    TextField summand2 = new TextField();
    TextField result = new TextField();
    
    StringConverter converter = new DoubleStringConverter();
    
    TextFormatter tf1 = new TextFormatter<>(converter, 0d);
    TextFormatter tf2 = new TextFormatter<>(converter, 0d);
    TextFormatter tfRes = new TextFormatter<>(converter, 0d);
    
    summand1.setTextFormatter(tf1);
    summand2.setTextFormatter(tf2);
    result.setTextFormatter(tfRes);
    
    tfRes.valueProperty().bind(
            Bindings.createObjectBinding(() -> tf1.getValue() + tf2.getValue(),
                    tf1.valueProperty(),
                    tf2.valueProperty()));
    
    result.setEditable(false);
    

    This allows you to assign the value using the TextFormatter, e.g.

    double someValue = 3d;
    tf1.setValue(someValue);
    

提交回复
热议问题