TextArea
TextArea in JavaFX. I’ll explain it, give examples in Java and FXML, and show how to use it effectively.
1️⃣ What is TextArea?
TextAreais a multi-line text input control.- Users can type, edit, copy, paste, and scroll through text.
- Useful for logs, messages, notes, or code editors.
2️⃣ Key Features
- Multi-line support – unlike
TextField. - Text wrapping – can wrap text automatically.
- Editable property – can make it read-only.
- Scrollbars – appear automatically if text exceeds the visible area.
- Get/Set text – use
getText()andsetText().
3️⃣ Simple Java Example
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextAreaExample extends Application {
@Override
public void start(Stage primaryStage) {
TextArea textArea = new TextArea();
textArea.setPromptText("Type something here...");
textArea.setPrefRowCount(10); // height in rows
textArea.setPrefColumnCount(30); // width in characters
textArea.setWrapText(true); // wrap long lines
// Set default text
textArea.setText("Hello! This is a TextArea example.\nYou can write multiple lines here.");
VBox root = new VBox(textArea);
root.setSpacing(10);
root.setStyle("-fx-padding: 20;");
Scene scene = new Scene(root, 400, 300);
primaryStage.setScene(scene);
primaryStage.setTitle("TextArea Example");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
✅ Explanation:
setWrapText(true)ensures long lines don’t scroll horizontally.setPrefRowCountandsetPrefColumnCountcontrol size.- You can get the current text with
textArea.getText().
4️⃣ FXML Example
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns="http://javafx.com/javafx/17.0.2" xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.TextAreaController"
spacing="10" style="-fx-padding: 20;">
<TextArea fx:id="textArea" promptText="Type something..." wrapText="true" prefRowCount="10" prefColumnCount="30"/>
</VBox>
Controller
package com.example;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
public class TextAreaController {
@FXML
private TextArea textArea;
@FXML
public void initialize() {
textArea.setText("Hello! You can write multiple lines here.\nThis is controlled from the controller.");
}
// Example method to get text
public String getTextContent() {
return textArea.getText();
}
}
5️⃣ Notes
- Read-only:
textArea.setEditable(false); - Appending text:
textArea.appendText("\nNew line added!"); - Scrolling: Scrolls automatically when text exceeds area.
- Can be combined with buttons to save, clear, or process text.