将微调器绑定到另一个微调器的fixedValue * theValue的乘积
我有一个标签女巫从tableView中计算总数,让我们调用它 标签总数它与表格的可观察列表项目的总和有关; 另一个是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 :(得分: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);
}
}