JavaFX: The setText() method

This entry is part 28 of 55 in the series JavaFX

It is interesting that we would usually get the input from the user but for a TextField, you can actually set a text inside the TextField if nothing is entered.

If nothing is entered and that you have clicked the submit button, the text that you have set using setText() method will be entered.

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) {
        launch(args);
    }

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

    TextField txtField;

    @Override
    public void start(Stage stage) {

        lbl.setMinWidth(100);
        lbl.setAlignment(Pos.BOTTOM_LEFT);

        Label lblEnter = new Label("Enter Text:");
        lblEnter.setMinWidth(100);
        lblEnter.setAlignment(Pos.BOTTOM_RIGHT);

        txtField = new TextField();
        txtField.setPrefWidth(200);
        txtField.setText("Before You Entered Anything");

        Button btnOK = new Button("OK");
        btnOK.setMinWidth(75);
        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));
        paneButton.setAlignment(Pos.BOTTOM_CENTER);

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

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

    public void buttonOK() {

        String message;

        message = txtField.getText();

        lbl.setText(message);

    }

}

So now if you just click on OK button, you will get an output as shown below:

setText

Series Navigation<< JavaFX: Entering text using TextField
JavaFX: Creating checkboxes >>

Leave a comment

Leave a Reply