0

Is there anyway I can do a for loop to create multiple textfields. Say I want like 20 text fields...do I have to create them individually?

3
  • Yes... just write a for loop and create the text fields inside it. It's not really clear what the question is. Commented Jan 11, 2016 at 1:06
  • How do I name it like tetxfield1 textfield2 etc... Commented Jan 11, 2016 at 1:35
  • If you need to refer to them outside the loop, put them in an array. Commented Jan 11, 2016 at 1:35

1 Answer 1

2

It's not really clear what your question is. Just write a for loop and create each TextField inside it.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TwentyTextFields extends Application {

    @Override
    public void start(Stage primaryStage) {

        final int numTextFields = 20 ;
        TextField[] textFields = new TextField[numTextFields];
        VBox root = new VBox(5);
        for (int i = 1; i <= numTextFields; i++) {
            TextField tf = new TextField();
            String name = "Text field "+i ;
            tf.setOnAction(e -> {
                System.out.println("Action on "+name+": text is "+tf.getText());
            });
            root.getChildren().add(tf);
            textFields[i-1] = tf ;
        }
        Scene scene = new Scene(new ScrollPane(root), 250, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.