user3822284
user3822284

Reputation:

Dynamically Adding TextField to javafx scene

I'm new to JavaFX. I want to interact with my scene.
For example : When I click on a button, I add a new Button, Textfield .. in it. however, i search but didn't find a satisfying answer!

my fxml file :

 <children>
    <Label layoutX="59.0" layoutY="83.0" text="message Type"/>
    <Button layoutX="157.0" layoutY="354.0" mnemonicParsing="false" onAction="#goBack" text="Revenir à la page precedente" />
    <Button layoutX="348.0" layoutY="354.0" mnemonicParsing="false" onAction="#goToDash" text="Go To Screen3" />
    <Button layoutX="375.0" layoutY="84.0" mnemonicParsing="false" onAction="#AddTextfiled" prefHeight="25.0" prefWidth="28.0" text="+" />
    <Button layoutX="375.0" layoutY="84.0" mnemonicParsing="false" onAction="#RemoveTextfield" prefHeight="25.0" prefWidth="28.0" text="-" />
    <TextField layoutX="212.0" layoutY="84.0" />
  </children>

my controller :

@FXML
private void goBack1(ActionEvent event){
   myController.setScreen(ScreensFramework.screenPreviousID);
}

@FXML
private void goToDash(ActionEvent event){
   myController.setScreen(ScreensFramework.screenDashID);
}
@FXML
private void AddTextField(ActionEvent event)  {     
 //add textfield on click}

@FXML
private void RemoveTextField(ActionEvent event)  {     
 //remove textfield on click

}

Upvotes: 1

Views: 6809

Answers (1)

WillBD
WillBD

Reputation: 1919

What you need to accomplish your goal is to give a fx:id to a container on your scene that can take children. lets say you have a stack pane defined as follows:

@FXML
    private VBox pane_main_grid;

where pane_main_grid is defined in the .fxml file with a fx:id as such. Great.

Now, using your aforementioned code.

@FXML
private void AddTextField(ActionEvent event)  {     
 TextField newField = new TextField();
 pane_main_grid.getChildren().add(newField);}

I'll leave the removing to you, all you need to do is come up with a way to keep track of the text fields you've created, and then when you want to remove one you do something like pane_main_grid.remove({index of text field to remove});

good luck!

Upvotes: 5

Related Questions