2015-10-08 119 views
0

我現在每次按下按鈕時都會動態地添加TextField和相應的ComboBox。有沒有辦法超出我的方法,然後使用VBox(fieldContainer)變量來獲取TextFieldComboBox值?從VBox獲取文本字段的值

編輯

我創建的用戶可以連接到數據庫並創建一個表的應用程序。用戶創建表格的場景的表名爲TextField,列名稱爲TextField,對應的ComboBox表示選擇列類型。

create table scene

當用戶點擊添加字段

,它產生另一個TextFieldComboBox波紋管當前一個,所以現在的表作爲兩列,等等......

然後我以後要搶用戶點擊創建時的值(帶下面的代碼),以便我可以將其組織爲適當的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

你能解釋你想要做什麼嗎?您何時想從這些控件中獲取值?您可能只需要將某些屬性與值綁定的對象添加到某種數據結構中,但沒有任何上下文,問題基本上是無法解析的。請創建一個[MCVE],顯示你想在這裏做什麼。 –

+0

@James_D我對這個問題進行了擴展。謝謝。 –

+0

謝謝。爲什麼不爲此使用'TableView'? –

回答

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中的相應控件中的值。

+0

工作很好,謝謝。我唯一需要改變的是我相信你在getLabel()方法上有一個錯誤,它需要返回label.get(); –

+0

'labelProperty()。get()'是我的意圖,雖然'label.get()'也可以。相應更新。 ('labelProperty().get()'允許覆蓋'labelProperty()',我沒有做'final',沒有違反'labelProperty()。get()'應該總是返回與' getLabel()'...) –

相關問題