How to add the rows dynamically on gridpane in Java FX?

Keibee picture Keibee · Mar 11, 2015 · Viewed 8.5k times · Source

I have a DB log in form on a single row as below,

    // Hostname Input
    Label hostName = new Label("Host:");
    grid.add(hostName, 0, 2);
    
    final TextField host = new TextField();
    host.getText();
    GridPane.setConstraints(host, 1, 2);
    grid.getChildren().add(host);
    
    // Port Input
    Label portName = new Label("Port:");
    grid.add(portName, 2, 2);

    final TextField port = new TextField();
    port.getText();
    GridPane.setConstraints(port, 3, 2);
    grid.getChildren().add(port);
    
    // SID Input
    Label sidName = new Label("SID:");
    grid.add(sidName, 4, 2);
    
    final TextField sid = new TextField();
    sid.getText();
    GridPane.setConstraints(sid, 5, 2);
    grid.getChildren().add(sid);
    
    // Username Input
    Label userName = new Label("Username:");
    grid.add(userName, 6, 2);
    
    final TextField user = new TextField();
    user.getText();
    GridPane.setConstraints(user, 7, 2);
    grid.getChildren().add(user);
    
    // Password Input
    Label pw = new Label("Password:");
    grid.add(pw, 8, 2);
    
    final TextField password = new PasswordField();
    password.getText();
    GridPane.setConstraints(password, 9, 2);
    grid.getChildren().add(password);

and I need to add more rows in the following case:

  1. When the txt input file has more than one line.

    ex) When there's one line, no need to extend, when two, need to add one more row.

  2. When the user click on the button to add the row.

Is it possible to do it in Java FX? Please help!!

Thank you for looking!

Answer

Juce picture Juce · Mar 11, 2015

Why don't you just use gridPane.addRow() when you are reading your textfile?

try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();
    int lineCounter = 0;

    while (line != null) {
        lineCounter++;
        if(lineCounter > 1){
            gridPane.addRow(lineCounter-1, nodeThatYouWant);
        }
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
}