How to create an array of TextFields in JavaFX

2019-09-22 03:22发布

问题:

I am converting an app written using Swing to JavaFX. I need an array of TextFields that I can manipulate collectively and as individual array members addressed by the array index. The following code works in Swing but I cannot find the equivalent in JavaFX, using TextField instead of JTextField. How can I achieve this in JavaFX?

private ArrayList<JTextField> fieldList= new ArrayList<JTextField>();

fieldList.add(fldCompletion);
fieldList.add(fldHrsToDate);
fieldList.add(fldHrsToComplete);

for(JTextField fl : fieldList) {
        fl.setText("");
        fl.setEnabled(true);    //FX equivalent is setDisable(false)
    }

fieldList.get(var).setText("");

回答1:

I also don't understand your question because this part of the code should work in JavaFX in the same way as it works in Java(Swing) and you are not telling us what your actual problem is. So I just make a wild guess. Maybe you have just forgotten to add your text field to the scene graph too and therefore your are seeing nothing.



回答2:

Apologies - it's my first post. I can instantiate the ArrayList -

private ArrayList<TextField> fieldList = new ArrayList<TextField>();

but when I try to add a TextField object to the array I get syntax errors:

fieldList.add(fldCompletion);

Multiple markers at this line - Syntax error, insert ")" to complete MethodDeclaration - Syntax error on token ".", @ expected after this token - Syntax error, insert "SimpleName" to complete QualifiedName - Syntax error, insert "Identifier (" to complete MethodHeaderName

This particular field is declared thus:

@FXML private TextField fldCompletion;


回答3:

This will do just fine

TextField[] txt = new TextField[beanFields.length];
for (int i=0; i<=beanFields.length-1; i++) {
                TextField textField = new TextField();
                txt[i] = textField;
                textField.setPrefWidth(200);
                textField.setPrefHeight(32);
}