2016-02-16 44 views
1

我正在使用簡單的計算器,用戶在TextField中輸入兩個數字,結果顯示在結果TextField中。我使用Double.parseDouble從輸入TextFields獲取文本並對其應用操作。但我無法將其傳遞給第三個輸入字段。我試圖將double結果轉換回String,但它不起作用。我怎樣才能簡單地將號碼傳遞給TextField?如何將數字傳遞給TextField JavaFX?

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

resultInput.setText(resultV); 

最後一行不起作用,格式不同。

+0

使用'String.valueOf(resultV)'' – saka1029

回答

1

沒有方法TextField.setText (double)

嘗試

resultInput.setText("" + resultV); 

,但我猜你真正想要的是結果被很好地格式化到也許兩位小數?

嘗試使用

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

你也可以使用 resultInput.setText(Double.toString(resultV));

2

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);