2015-10-08 27 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()'...) –