我每次按下按钮时都会动态添加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();
}
});
答案 0 :(得分:1)
您可以通过创建一个类来保存数据(如果我理解正确的话)将形成结果表的每一行。在创建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
各个rand()
中相应控件中的值。