[英]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.