如何在JavaFx中将textField与其他textField绑定。例如
textFieldTotal.textProperty.bind(Bindings.multiply(textFieldAmount.textProperty,
textFieldPrice.textProperty));
答案 0 :(得分:3)
您的问题很模糊,但是我会猜测。基本上,您需要创建一些附加的Property
和Binding
对象。
首先,为您的两个TextField
节点创建属性。然后,您将使用StringConverter
绑定它们,将输入的文本转换为双精度。
最后,创建一个“总计”属性,将两个字段相乘并将它们显示在Label
中。
这是一个非常简单的应用程序来进行测试:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import javafx.util.converter.DoubleStringConverter;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Simple Interface
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(10));
// Quantity
HBox hBoxQuantity = new HBox(5);
hBoxQuantity.setAlignment(Pos.CENTER);
TextField txtQuantity = new TextField();
hBoxQuantity.getChildren().addAll(
new Label("Quantity:"),
txtQuantity
);
// Price
HBox hBoxPrice = new HBox(5);
hBoxPrice.setAlignment(Pos.CENTER);
TextField txtPrice = new TextField();
hBoxPrice.getChildren().addAll(
new Label("Price:"),
txtPrice
);
// Total
HBox hBoxTotal = new HBox(5);
hBoxTotal.setAlignment(Pos.CENTER);
Label lblTotal = new Label();
hBoxTotal.getChildren().addAll(
new Label("Total: $"),
lblTotal
);
// Properties used for bindings
DoubleProperty price = new SimpleDoubleProperty();
DoubleProperty quantity = new SimpleDoubleProperty();
DoubleProperty total = new SimpleDoubleProperty();
// Bind the total to price x quantity
total.bind(price.multiply(quantity));
// Setup the converters to get the input from the textfields
StringConverter<? extends Number> converter = new DoubleStringConverter();
// Bind the text field entries to their properties
Bindings.bindBidirectional(txtPrice.textProperty(), price, (StringConverter<Number>) converter);
Bindings.bindBidirectional(txtQuantity.textProperty(), quantity, (StringConverter<Number>) converter);
// Bind the total label
lblTotal.textProperty().bind(total.asString());
// Add all nodes to stage
root.getChildren().addAll(hBoxPrice, hBoxQuantity, hBoxTotal);
// Show the stage
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.setScene(new Scene(root));
primaryStage.setTitle("Sample");
primaryStage.show();
}
}
结果:
这是您的主意吗?
注意:这显然不包括任何错误检查或输入限制,因此,如果在任一{{1}中输入非数字
String
,您将收到一条错误消息。 }。