2015-12-05 24 views
0

綁定微調器fixedValue的產品fixedValue時間theValue的產品* theValue另一個微調JavaFX綁定微調到另一個微調

我有一個標籤巫婆從的tableView計算總就讓我們把它 標籤totalHt女巫它與表中可觀察的清單項目總數的總和有界; 另一個是tvaSpinner女巫是用戶可編輯輸入一個TVA(10%)價值。需要 ,最後一個是 標籤totalWithTVA女巫有界到的產品:

totalHt * (tvaSpinner.valueProperty()/100) . 

這裏是我想要做的一個例子:

public class BindingSpinnerExample { 
@FXML 
Label totalHt; 
@FXML 
Spinner<Double> taxSpinner; 
@FXML 
Label totalWithTVA; 


taxSpinner.setEditable(true); 

我想綁定totalWithTVA到:

totalWithTVA = totalHt * (taxSpinner.valueProperty()/100) 

,但我不知道如何做到這一點招標

} 
+0

你的描述有點難以遵循。請提供一個[MCVE](http://stackoverflow.com/help/mcve) – hotzst

+1

另外,爲什麼你會同時創建'totalSpinner'和'totalWithTax' spinners?你永遠不希望用戶改變這些值,所以爲什麼不把它們標籤? –

回答

0

這有點難看。您的Spinner(推測)是Spinner<Double>,所以它有一個ReadOnlyObjectProperty<Double>valueProperty()。算術計算方法multiply(),divide()等定義爲ReadOnlyDoubleProperty,而不是ReadOnlyObjectProperty<Double>,因此您需要將屬性轉換爲ReadOnlyDoubleProperty。有一個靜態的ReadOnlyDoubleProperty.readOnlyDoubleProperty(ReadOnlyObjectProperty<Double>) method可以爲你做這個轉換。

所以,你需要做這樣的事情

DoubleBinding total = totalHtProperty.multiply(ReadOnlyDoubleProperty 
    .readOnlyDoubleProperty(taxSpinner.valueProperty()).divide(100)); 

然後當然

totalWithTVA.textProperty().bind(total.asString()); 

其中totalHtProperty是某種DoubleExpression與在totalHt標籤顯示的值(我假設你正在計算這個地方)。

這裏有一個SSCCE:

import javafx.application.Application; 
import javafx.beans.binding.DoubleBinding; 
import javafx.beans.property.ReadOnlyDoubleProperty; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.Label; 
import javafx.scene.control.Spinner; 
import javafx.scene.layout.GridPane; 
import javafx.stage.Stage; 

public class BoundSpinners extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     Spinner<Double> taxSpinner = new Spinner<>(0.0, 100.0, 6.0, 0.5); 
     Spinner<Double> priceSpinner = new Spinner<>(0, Double.MAX_VALUE, 0, 10); 

     DoubleBinding taxAmount = 
       ReadOnlyDoubleProperty.readOnlyDoubleProperty(priceSpinner.valueProperty()) 
        .multiply(ReadOnlyDoubleProperty.readOnlyDoubleProperty(taxSpinner.valueProperty()).divide(100)); 

     Label taxLabel = new Label(); 
     taxLabel.textProperty().bind(taxAmount.asString("$%.2f")); 

     GridPane root = new GridPane(); 
     root.addRow(0, new Label("Price:"), priceSpinner); 
     root.addRow(1, new Label("Tax rate:"), taxSpinner); 
     root.addRow(2, new Label("Tax due:"), taxLabel); 

     root.setAlignment(Pos.CENTER); 

     Scene scene = new Scene(root, 400, 400); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 
+0

spinner.valueProperty()以及spinner.valueProperty()中沒有綁定方法。 –

+0

是的,你是對的。 'Spinner.valueProperty()'是一個'ReadOnlyProperty'。您需要改爲使用'valueFactory'的'valueProperty'。我更新了答案。 (我仍然不明白你爲什麼會用'Spinner'。) –

+0

好吧,我想通過使用標籤來表達你的意思,我最好使用一個微調框來表示我的總數,因爲我需要正確的數字格式,而不是標籤的字符串。但確定有一個字符串格式化程序來這樣做。 –

相關問題