Search code examples
javajavafxuser-input

How do I clear the input field of a TextInputDialog?


My JavaFX program has a series of prompts asking the user for information. Rather than create a new TextInputDialog for each prompt, I want to create a single TextInputDialog and reuse it for multiple prompts.

import java.util.Optional;
import javafx.application.Application;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;

public class InventoryList extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        Optional<String> name;
        Optional<String> price;

        // Fetch user input
        TextInputDialog textDialog = new TextInputDialog();
        textDialog.setTitle("Create new item");
        textDialog.setHeaderText(null);

        textDialog.setContentText("Enter item name:");
        name = textDialog.showAndWait();

        textDialog.setContentText("Enter item price:");
        price = textDialog.showAndWait();
    }
}

Unfortunately, the user's typed input from the first prompt...

First prompt

Isn't cleared when starting the second prompt.

second prompt.

Is it possible to clear the textfield between prompts?


Solution

  • textDialog.getEditor().clear();