nammrick
nammrick

Reputation: 109

JavaFX dynamically adding new text fields

I'm writing a program that will allow a user to add new, empty text fields in the event that more data needs to be added to the form. I'm having trouble understanding how to set the coordinates for each new field that is added to my GridPane. For example,

            btnClick.setOnAction(new EventHandler<ActionEvent>(){
    public void handle(ActionEvent e)
{
    TextField text = new TextField();
    primaryPane.add(text, 5 , 6);
}});

will only result in one new text field being added in position (5,6). How can the code be altered to allow a user to add as many fields as they want, each one displaying after the other. I know that I could use a loop for a determined amount of new fields, however the user should be able to create any number. Thanks in advance for any help.

Nathan

Upvotes: 3

Views: 6666

Answers (1)

Keyur Bhanderi
Keyur Bhanderi

Reputation: 1544

This code help you.

public class AddTextField extends Application {
int i = 1;

@Override
public void start(Stage primaryStage) {
    GridPane root = new GridPane();
    root.setHgap(10);
    root.setVgap(10);
    TextField textField[] = new TextField[15];
    Button btn = new Button("Add TextField");
    root.add(btn, 0, 0);
    btn.setOnAction(e -> {
        textField[i] = new TextField();
        root.add(textField[i], 5, i);
        i = i + 1;

    });

    final Scene scene = new Scene(root, 500, 400);
    primaryStage.setScene(scene);
    primaryStage.show();

}

public static void main(String[] args) {
    launch(args);
}}

Upvotes: 5

Related Questions