JavaFX - TextField



The text field is a graphical user interface component used to accept user input in the form of text. It is the most easiest way of interaction between system and user. We can find a textfield inside a form or dialog window as shown in the below figure −

JavaFX textfield

TextField in JavaFX

In JavaFX, the TextField class represents the text field which is a part of the package named javafx.scene.control. Using this we can accept input from the user and read it to our application. This class inherits the TextInputControl which is the base class of all the text controls class. To create a text field, instantiate the TextField class using any of the below constructors −

  • TextField() − This constructor will create an empty textfield.

  • TextField(String str) − It is the parameterized constructor which constructs a textfield with the specified text.

Note that in the latest versions of JavaFX, the TextField class accepts only a single line.

Example

In the following JavaFX program, we will create a hyperlink as a text. Save this code in a file with the name JavafxTextfield.java.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavafxTextfield extends Application {
   public void start(Stage stage) {
      //Creating nodes
      TextField textField1 = new TextField("Enter your name");
      TextField textField2 = new TextField("Enter your e-mail");
      //Creating labels
      Label label1 = new Label("Name: ");
      Label label2 = new Label("Email: ");
      //Adding labels for nodes
      HBox box = new HBox(5);
      box.setPadding(new Insets(25, 5 , 5, 50));
      box.getChildren().addAll(label1, textField1, label2, textField2);
      //Setting the stage
      Scene scene = new Scene(box, 595, 150, Color.BEIGE);
      stage.setTitle("Text Field Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

To compile and execute the saved Java file from the command prompt, use the following commands −

javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxTextfield.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxTextfield

Output

When we execute, the above program will generate the following output.

TextField Output
Advertisements