JavaFX: Entering text using TextField

This entry is part 27 of 55 in the series JavaFX

TextField is probably the most common control among all the UI input Elements.  TextField is for user to input a single line of text.

By now, it should be rather easy for us to display the TextField in the scene.

To get the input string into a string variable, it is equally easy.  As in the example below, we use the getText() method as below.

package enteringtext;

import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

public class EnteringText extends Application {

    public static void main(String[] args) {

    Label lbl = new Label("Entered Text Will Show Here");

    TextField txtField;

    public void start(Stage stage) {


        Label lblEnter = new Label("Enter Text:");

        txtField = new TextField();

        Button btnOK = new Button("OK");
        btnOK.setOnAction(e -> buttonOK());

        HBox paneLabel = new HBox(20, lbl);

        paneLabel.setPadding(new Insets(50));

        HBox paneField = new HBox(20, lblEnter, txtField);
        paneField.setPadding(new Insets(10));

        HBox paneButton = new HBox(20, btnOK);
        paneButton.setPadding(new Insets(10));

        VBox pane = new VBox(10, paneLabel, paneField, paneButton);

        Scene scene = new Scene(pane);
        stage.setTitle("Enter A Text");;

    public void buttonOK() {

        String message;

        message = txtField.getText();






Series Navigation<< JavaFX: Hbox with priority always
JavaFX: The setText() method >>

Leave a comment

Leave a Reply