How to pass number to TextField JavaFX?

穿精又带淫゛_ 提交于 2019-12-02 12:57:44

问题


I am working on simple calculator, where users input two numbers in TextField and the result is displayed in result TextField. I used Double.parseDouble to get the text from input TextFields and apply the operation on it. But I am unable to pass it to third input field. I tried to cast back the double result to String but It didn't work. How can I simply pass number to TextField?

double num1 = Double.parseDouble(numberInput1.getText());
double num2 = Double.parseDouble(numberInput2.getText());
double resultV = (num1 + num2);

resultInput.setText(resultV);

The last line is not working and as the format is different.


回答1:


There is no method TextField.setText (double)

try

resultInput.setText("" + resultV);

but I guess what you really want is for the result to be nicely formatted to maybe two decimal places?

try using

resultInput.setText(String.format ("%6.2f", resultV));



回答2:


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<Double> converter = new DoubleStringConverter();

TextFormatter<Double> tf1 = new TextFormatter<>(converter, 0d);
TextFormatter<Double> tf2 = new TextFormatter<>(converter, 0d);
TextFormatter<Double> 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);



回答3:


you can also use resultInput.setText(Double.toString(resultV));



来源:https://stackoverflow.com/questions/35421392/how-to-pass-number-to-textfield-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!