Issue
I'm a bit new to Java and I'm trying to make an User Interface in JavaFX that dinamically adds a TextField and an "edit" Button next to it whenever the user presses a "+" button. I understand that it is a good idea to try and store these buttons and text fields in a list, but I'm not sure how to have them put on the interface
ListView<Button> dinamicButtons = new ListView<Button>();
ListView<TextField> dinamicTextFields = new ListView<TextField>();
int quantityOfDinamicFieldsAdded =0;
Button add= new Button ("+");
add.setOnAction(e -> {
dinamicButtons .add(quantityOfDinamicFieldsAdded , new Button("Edit"));
dinamicTextFields .add(quantityOfDinamicFieldsAdded , new TextField("nome do Componente"));
quantityOfDinamicFieldsAdded ++;
//remove dinamically added buttons and text fields
for (int i=0 ; i<quantityOfDinamicFieldsAdded ; i++){
//add them all back
}
});
Solution
Here is a demo that adds a Button
and TextField
to ListView
. The POJO
just keeps track of the TextField's
prompt text and the Button's
text. The key to this is using a CellFactory
.
import java.util.concurrent.atomic.AtomicInteger;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* @author blj0011
*/
public class JavaFXTestingGround extends Application{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
ListView<CellData> listView = new ListView();
listView.setCellFactory((ListView<CellData> param) -> {
ListCell<CellData> cell = new ListCell<CellData>() {
TextField textField = new TextField();
Button button = new Button();
HBox hBox = new HBox(textField, button);
{
HBox.setHgrow(textField, Priority.ALWAYS);
}
@Override
protected void updateItem(CellData item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
textField.setPromptText(item.getTextFieldPromptText());
button.setText(item.getButtonText());
button.setOnAction((actionEvent) -> {
System.out.println("You clicked " + button.getText() + ". TextField Prompt text is " + textField.getPromptText() + ".");
});
setGraphic(hBox);
} else {
setGraphic(null);
}
}
};
return cell;
});
AtomicInteger i = new AtomicInteger(1);
Button button = new Button("Add Item");
button.setOnAction((event) -> {
listView.getItems().add(new CellData("Prompt Text: " + i.get(), "Button: " + i.getAndIncrement()));
});
VBox root = new VBox(button, listView);
stage.setScene(new Scene(root));
stage.show();
}
}
Answered By - Sedrick