[英]Getting value of a Text Field from a VBox
我当前每次按下按钮都会动态添加一个TextField
和一个对应的ComboBox
。 在我的方法之外,还有什么方法可以使用VBox
(fieldContainer)变量来获取TextField
和ComboBox
值?
编辑
我正在创建一个应用程序,用户可以在其中连接到数据库并创建表。 在其中用户创建表的场景具有TextField
表名和一个TextField
用于与对应的列名ComboBox
以选择列类型。
当用户单击添加字段时,它将在当前字段下方生成另一个TextField
和ComboBox
,因此现在该表分为两列,依此类推...
然后,我以后想在用户单击create时获取值(使用下面的代码),以便将其组织为适当的SQL语句。
码
addTableField.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
HBox box = new HBox(10);
ComboBox<String> combo = new ComboBox<String>(fieldTypes);
combo.setPromptText("type");
TextField field = new TextField();
field.setPromptText("field label");
box.getChildren().addAll(field, combo);
fieldContainer.getChildren().addAll(box);
window.sizeToScene();
}
});
您可以通过创建一个类来保存数据(如果我理解正确的话),这些数据将构成结果表的每一行。 创建HBox
,从此类创建一个对象,将对象中的数据绑定到控件中的数据,然后将该对象添加到列表中。 然后,您可以仅检查列表的内容。
就像是:
public class Row {
private final StringProperty label = new SimpleStringProperty() ;
public StringProperty labelProperty() {
return label ;
}
public final String getLabel() {
return labelProperty().get();
}
public final void setLabel(String label) {
labelProperty().set(label);
}
public final StringProperty type = new SimpleStringProperty();
public StringProperty typeProperty() {
return type ;
}
public final String getType() {
return typeProperty().get();
}
public final void setType(String type) {
typeProperty().set(type);
}
}
现在,在您的主要代码中,您可以执行以下操作:
final List<Row> rows = new ArrayList<>();
addTableField.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
HBox box = new HBox(10);
ComboBox<String> combo = new ComboBox<String>(fieldTypes);
combo.setPromptText("type");
TextField field = new TextField();
field.setPromptText("field label");
box.getChildren().addAll(field, combo);
fieldContainer.getChildren().addAll(box);
Row row = new Row();
rows.add(row);
row.labelProperty().bind(field.textProperty());
row.typeProperty().bind(combo.valueProperty()); // might need to worry about null values...
window.sizeToScene();
}
});
然后,当用户单击“创建”时,您可以遍历rows
,该行将为您创建的每个HBox
都有一个对象,而getLabel()
和getType()
给出相应HBox
相应控件中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.