JavaFX TextField tutorial

0
TextField is used for single line text input.

We can edit text or enter new text string in textfield.

TextField Constructors :

  • TextField()
    Creates a TextField with empty text content.
  • TextField(String text)
    Creates a TextField with initial text content.
Methods :

We Use these Methods for editing text 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 textfield.
  • paste() – set the contents in the clipboard into this text and replace the current selection.

Example of text field:


package javafxtuts;

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.stage.Stage;
/**
 *
 * @author javafxtuts
 */
public class Javafxtuts extends Application {

  @Override
  public void start(Stage primaryStage) {
      
      // setting title of application
      primaryStage.setTitle("javafxtuts.com");
      //creating HBox layout
      HBox hb = new HBox();
      
      Label lb =new Label(" School Name : ");
      //to set space for label from other nodes of VBox
      lb.setPadding(new Insets(10));
      //to Create a text field
      TextField tf =new TextField();
      tf.setText("Enter Text Here");
      //To select whole text in the textfield 
      tf.selectAll();
      // to set space for hb layout
      hb.setPadding(new Insets(10));
      
      //add all children of Vbox layout(root)
      hb.getChildren().addAll(lb,tf);
      Scene scene = new Scene(hb, 400, 300);
      primaryStage.setScene(scene);
      primaryStage.show();
  }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

Output :

Explanation of text Filed program:

    • To create a text field we do AS

TextField tf =new TextField();

    • setText() method is used to set the text in the text field when application execute. So

tf.setText("Enter Text Here");

    • To select whole text in the textfield

tf.selectAll();

Share.

Leave A Reply