TextField
TextField in JavaFX. It’s simpler than TextArea but very important for single-line text input.
1️⃣ What is TextField?
TextFieldis a single-line input control for text.- Users can type, edit, copy, paste text.
- Often used for forms, search boxes, or username/password input.
2️⃣ Key Features
- Single-line input – unlike
TextArea. - Prompt text – shows a hint inside the field.
- Editable property – can make it read-only.
- Max length – can be controlled programmatically.
- Text property – use
getText()/setText().
3️⃣ Simple Java Example
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextFieldExample extends Application {
@Override
public void start(Stage primaryStage) {
TextField textField = new TextField();
textField.setPromptText("Enter your name"); // placeholder text
Button btn = new Button("Submit");
btn.setOnAction(e -> {
String input = textField.getText();
System.out.println("You entered: " + input);
});
VBox root = new VBox(10, textField, btn);
root.setStyle("-fx-padding: 20;");
Scene scene = new Scene(root, 300, 150);
primaryStage.setScene(scene);
primaryStage.setTitle("TextField Example");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
✅ Explanation:
setPromptText()shows a placeholder hint.getText()retrieves what the user typed.setText("Default text")sets the initial content.- Can attach event handlers for buttons or key events.
4️⃣ FXML Example
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns="http://javafx.com/javafx/17.0.2" xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.TextFieldController"
spacing="10" style="-fx-padding: 20;">
<TextField fx:id="textField" promptText="Enter your name"/>
<Button text="Submit" onAction="#handleSubmit"/>
</VBox>
Controller
package com.example;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public class TextFieldController {
@FXML
private TextField textField;
@FXML
private void handleSubmit() {
String input = textField.getText();
System.out.println("You entered: " + input);
}
}
5️⃣ Notes
- Read-only:
textField.setEditable(false); - Clear text:
textField.clear(); - Listen for changes:
textField.textProperty().addListener((obs, oldText, newText) -> {
System.out.println("Text changed: " + newText);
});
- Perfect for search boxes, login forms, or any single-line input.