TextFlow
In JavaFX, a TextFlow is a layout container used to display rich text, where multiple Text nodes can have different styles, colors, fonts, and still flow together like a paragraph.
- Great for highlighted text, rich labels, or chat messages.
- It automatically wraps text to fit the width.
Basic Example
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class TextFlowExample extends Application {
@Override
public void start(Stage stage) {
// Create individual Text nodes
Text text1 = new Text("Hello, ");
text1.setFill(Color.BLUE);
text1.setFont(Font.font("Arial", 20));
Text text2 = new Text("this is ");
text2.setFill(Color.BLACK);
text2.setFont(Font.font("Verdana", 18));
Text text3 = new Text("JavaFX TextFlow!");
text3.setFill(Color.RED);
text3.setFont(Font.font("Courier New", 22));
// Combine them into TextFlow
TextFlow textFlow = new TextFlow(text1, text2, text3);
textFlow.setPrefWidth(400); // wrap text at 400px
textFlow.setLineSpacing(5); // space between lines
Scene scene = new Scene(textFlow, 450, 150);
stage.setTitle("TextFlow Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Result:
- Blue “Hello,”
- Black “this is”
- Red “JavaFX TextFlow!”
- Automatically wraps if the window is narrower than 400px
Key Properties
textFlow.getChildren(); // get all Text nodes
textFlow.setLineSpacing(5); // vertical spacing between lines
textFlow.setTextAlignment(TextAlignment.JUSTIFY); // LEFT, CENTER, RIGHT, JUSTIFY
textFlow.setPrefWidth(400); // wrap width
Each Text node can have:
text.setFont(Font.font("Arial", 20));
text.setFill(Color.RED);
text.setUnderline(true);
text.setStrikethrough(true);
FXML Version
<TextFlow xmlns:fx="http://javafx.com/fxml" prefWidth="400" lineSpacing="5">
<children>
<Text text="Hello, " fill="BLUE" />
<Text text="this is " fill="BLACK" />
<Text text="JavaFX TextFlow!" fill="RED" />
</children>
</TextFlow>
Use Cases
- Display rich text with multiple colors/fonts
- Chat messages or logs
- Syntax-highlighted code editor
- Notes or documentation panels
💡 Tip: Combine TextFlow with a ScrollPane to create scrollable text areas:
ScrollPane scroll = new ScrollPane(textFlow);
scroll.setFitToWidth(true);
This is how chat apps or console outputs handle styled text.