簡體   English   中英

如何將數字傳遞給TextField JavaFX?

[英]How to pass number to TextField JavaFX?

我正在使用簡單的計算器,其中用戶在TextField輸入兩個數字,結果顯示在result TextField 我使用Double.parseDouble從輸入TextFields中獲取文本並對其進行操作。 但是我無法將其傳遞給第三個輸入字段。 我試圖將double結果回退到String,但是沒有用。 如何簡單地將數字傳遞給TextField?

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

resultInput.setText(resultV);

最后一行不起作用,並且格式不同。

setText需要一個String作為參數。 您需要將結果轉換為String ,例如,使用Double.toString

然而,在這種情況下,我建議您加入TextFormatterTextField ,它允許你指定/對不同類型的輸入值String使用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);

這使您可以使用TextFormatter來分配值,例如

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

沒有方法TextField.setText (double)

嘗試

resultInput.setText("" + resultV);

但是我想您真正想要的是將結果格式化為大約兩位小數的格式嗎?

嘗試使用

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

您還可以使用resultInput.setText(Double.toString(resultV));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM