JavaFX | TextInputDialog

Опубликовано: 13 Февраля, 2022

TextInputDialog является частью библиотеки JavaFX. TextInputDialog - это диалоговое окно, которое позволяет пользователю вводить текст, и диалоговое окно содержит текст заголовка, TextField и кнопки подтверждения.

Конструкторами класса TextInputDialog являются:

  1. TextInputDialog () : создает диалог ввода текста без исходного текста.
  2. TextInputDialog (String txt) : создает диалог ввода текста с исходным текстом txt .

Обычно используемые методы:

метод объяснение
getDefaultValue () возвращает значение по умолчанию для диалогового окна ввода текста
getEditor () возвращает редактор диалогового окна ввода текста
setHeaderText (String s) устанавливает текст заголовка диалогового окна ввода текста

Below programs illustrate the TextInputDialog class:

  1. Program to create a TextInputDialog and add it to the stage: This program creates a TextInputDialog with an initial text and a header text. The header text is set using setHeaderText() function. Button is indicated by the name d and text input dialog will have name td. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results. The TextInputDialog will be shown on the click of the button.
    // Java Program to create a text input
    // dialog and add it to the stage
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.*;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.control.*;
    import javafx.stage.Stage;
    import javafx.scene.control.Alert.AlertType;
    import java.time.LocalDate;
    public class TextInputDialog_1 extends Application {
      
        // launch the application
        public void start(Stage s)
        {
            // set title for the stage
            s.setTitle("creating textInput dialog");
      
            // create a tile pane
            TilePane r = new TilePane();
      
            // create a text input dialog
            TextInputDialog td = new TextInputDialog("enter any text");
      
            // setHeaderText
            td.setHeaderText("enter your name");
      
            // create a button
            Button d = new Button("click");
      
            // create a event handler
            EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
                public void handle(ActionEvent e)
                {
                    // show the text input dialog
                    td.show();
                }
            };
      
            // set on action of event
            d.setOnAction(event);
      
            // add button and label
            r.getChildren().add(d);
      
            // create a scene
            Scene sc = new Scene(r, 500, 300);
      
            // set the scene
            s.setScene(sc);
      
            s.show();
        }
      
        public static void main(String args[])
        {
            // launch the application
            launch(args);
        }
    }

    Output:

  2. Program to create a TextInputDialog and add a label to display the text entered: This program creates a TextInputDialog (td). Button indicated by the name d and TextInputDialog will have name td. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results.when the button will be clicked the text input dialog will be shown. A label named l will be created that will be added to the scene which will show the text that the user inputs in the dialog.
    // Java Program to create a text input dialog
    // and add a label to display the text entered
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.*;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.control.*;
    import javafx.stage.Stage;
    import javafx.scene.control.Alert.AlertType;
    import java.time.LocalDate;
    public class TextInputDialog_2 extends Application {
      
        // launch the application
        public void start(Stage s)
        {
            // set title for the stage
            s.setTitle("creating textInput dialog");
      
            // create a tile pane
            TilePane r = new TilePane();
      
            // create a label to show the input in text dialog
            Label l = new Label("no text input");
      
            // create a text input dialog
            TextInputDialog td = new TextInputDialog();
      
            // create a button
            Button d = new Button("click");
      
            // create a event handler
            EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
                public void handle(ActionEvent e)
                {
                    // show the text input dialog
                    td.showAndWait();
      
                    // set the text of the label
                    l.setText(td.getEditor().getText());
                }
            };
      
            // set on action of event
            d.setOnAction(event);
      
            // add button and label
            r.getChildren().add(d);
            r.getChildren().add(l);
      
            // create a scene
            Scene sc = new Scene(r, 500, 300);
      
            // set the scene
            s.setScene(sc);
      
            s.show();
        }
      
        public static void main(String args[])
        {
            // launch the application
            launch(args);
        }
    }

    Output:

    Note : The above programs might not run in an online IDE please use an offline IDE.

    Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextInputDialog.html

    Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.