JavaFX Tutorial - JavaFX TextField








The TextField is for single ling text input.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
// w w  w .jav a  2 s . c o  m
public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }
  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);

    TextField notification = new TextField ();
    notification.setText("Label");
    
    notification.clear();
    
    GridPane grid = new GridPane();
    grid.setVgap(4);
    grid.setHgap(10);
    grid.setPadding(new Insets(5, 5, 5, 5));
    grid.add(new Label("To: "), 0, 0);
    grid.add(notification, 1, 0);
    
    Group root = (Group) scene.getRoot();
    root.getChildren().add(grid);
    stage.setScene(scene);
    stage.show();
  }
}

TextField and PasswordField extend the TextInput class which is a super class for all the text controls in the JavaFX.

The code above generates the following result.

null




Creating a Text Field

We can use the constructors from TextField class to create text fields.

The TextField is only a text input box with cursor, usually we need a Label control to tell the purpose of the text field. The following code create a Label control to mark the cooresponding text field is for name input. Then it creates a TextField object. After that it use a HBox to layout the Label and TextField.

Label label1 = new Label("Name:");
TextField textField = new TextField ();
HBox hb = new HBox();
hb.getChildren().addAll(label1, textField);
hb.setSpacing(10);

To create a text field with the predefined text

TextField textField = new TextField("java2s.com")




Text in TextField

To get the value from a text field, call the getText method.

setPrefColumnCount method from the TextInput sets the size of the text field. by setting the maximum number of characters it can display at one time.

We can use prompt captions to notify users the purpose of the text field. The setPromptText method defines the string that appears in the text field. The prompt text cannot be obtained through the getText method.

The following code shows how to set Prompt Text For TextField

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
/*from   w w w .j  a v a  2  s.co  m*/
public class Main extends Application {

  @Override
  public void start(Stage stage) {
    Group root = new Group();
    Scene scene = new Scene(root, 300, 150);
    stage.setScene(scene);
    stage.setTitle("Text Field Sample");

    GridPane grid = new GridPane();
    grid.setPadding(new Insets(10, 10, 10, 10));
    grid.setVgap(5);
    grid.setHgap(5);

    scene.setRoot(grid);

    final TextField name = new TextField();
    name.setPromptText("Enter your first name.");
    name.setPrefColumnCount(10);
    name.getText();
    GridPane.setConstraints(name, 0, 0);
    grid.getChildren().add(name);


    stage.show();
  }

  public static void main(String[] args) {
    launch(args);
  }
}

The following list has helpful methods we can use to do the text editing in text field.

  • copy() - set the selected text to the clipboard.
  • cut() - set the selected text to the clipboard and remove the current selection.
  • selectAll() - selects all text in the text input.
  • paste() - set the contents in the clipboard into this text and replace the current selection.

The code above generates the following result.

null

Example

The following code shows how to bind string value from TextField to Stage Title.

// ww w.  ja v  a  2 s .  c om
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {
  StringProperty title = new SimpleStringProperty();
  
  public static void main(String[] args) {
    Application.launch(args);
  }
  
  @Override
  public void start(Stage stage) {
    TextField titleTextField;
    titleTextField = new TextField();
    titleTextField.setText("Stage Coach");
    titleTextField.setPrefColumnCount(15);

    HBox hBox = new HBox();
    hBox.setSpacing(10);
    hBox.getChildren().add(new Label("title:"));
    hBox.getChildren().add(titleTextField);

    Scene scene  = new Scene(hBox,270,270);
    title.bind(titleTextField.textProperty());
    
    stage.setScene(scene);
    stage.titleProperty().bind(title);


    stage.show();
  }
}

The code above generates the following result.

null

Example 2

The following code shows how to add ContextMenu to TextField.

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
/*from  ww  w.  j  a v a 2  s.com*/
public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);

    TextField notification = new TextField();

    final ContextMenu contextMenu = new ContextMenu();
    contextMenu.setOnShowing(new EventHandler<WindowEvent>() {
      public void handle(WindowEvent e) {
        System.out.println("showing");
      }
    });
    contextMenu.setOnShown(new EventHandler<WindowEvent>() {
      public void handle(WindowEvent e) {
        System.out.println("shown");
      }
    });

    MenuItem item1 = new MenuItem("About");
    item1.setOnAction(new EventHandler<ActionEvent>() {
      public void handle(ActionEvent e) {
        System.out.println("About");
      }
    });
    MenuItem item2 = new MenuItem("Preferences");
    item2.setOnAction(new EventHandler<ActionEvent>() {
      public void handle(ActionEvent e) {
        System.out.println("Preferences");
      }
    });
    contextMenu.getItems().addAll(item1, item2);

    notification.setContextMenu(contextMenu);
    GridPane grid = new GridPane();
    grid.setVgap(4);
    grid.setHgap(10);
    grid.setPadding(new Insets(5, 5, 5, 5));
    grid.add(new Label("To: "), 0, 0);
    grid.add(notification, 1, 0);

    Group root = (Group) scene.getRoot();
    root.getChildren().add(grid);
    stage.setScene(scene);
    stage.show();
  }
}

The code above generates the following result.

null

Example 3

Override replaceText and replaceSelection to create customized TextField

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
// w  w w. j  a  va2  s .co m
public class Main extends Application {
  public static void main(String[] args) {
    Application.launch(args);
  }

  @Override
  public void start(Stage primaryStage) {
    Group root = new Group();
    Scene scene = new Scene(root, 300, 250, Color.WHITE);

    TextField field = new TextField() {
      @Override
      public void replaceText(int start, int end, String text) {
        if (!text.matches("[a-z]")) {
          super.replaceText(start, end, text);
        }
      }

      @Override
      public void replaceSelection(String text) {
        if (!text.matches("[a-z]")) {
          super.replaceSelection(text);
        }
      }
    };

    root.getChildren().add(field);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

The code above generates the following result.

null