In the fxml class of my JavaFx application I want to add a large body of text using minimal components (instead of adding multiple labels per line). I would also like to create varying styles of text in the same component. What component should I use (e.g TextArea) and how would I go about create multiple styles inside it (using css).
Asked
Active
Viewed 5,740 times
1 Answers
8
Use a TextFlow and add Text to it. You can style individual Text component with different style using css on them.
Complete example :
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class TextFlowExample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Text text1 = new Text("First Text\n");
text1.setStyle("-fx-font-size: 20; -fx-fill: darkred;");
Text text2 = new Text("\nSecond Text");
text2.setStyle("-fx-font-size: 30; -fx-fill: goldenrod;");
TextFlow textFlow = new TextFlow(text1, text2);
primaryStage.setScene(new Scene(textFlow, 200, 200));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output
Equivalent FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.*?>
<?import java.lang.*?>
<?import javafx.scene.text.*?>
<TextFlow lineSpacing="10.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" textAlignment="CENTER" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Text strokeType="OUTSIDE" strokeWidth="0.0" style="-fx-font-size: 20; -fx-fill: darkred;" text=" First Text" />
<Text strokeType="OUTSIDE" strokeWidth="0.0" style="-fx-font-size: 30; -fx-fill: goldenrod;" text=" Second Text" />
</children>
</TextFlow>

ItachiUchiha
- 36,135
- 10
- 122
- 176
-
I found this quite a useful tutorial on TextFlow - https://wiki.openjdk.java.net/display/OpenJFX/Rich+Text+API+Samples – Josh Beaver Apr 30 '15 at 18:22
-
but "-fx-text-fill: color;" and "-fx-fill: color;" isn't changing the text color – Josh Beaver Apr 30 '15 at 18:24
-
I have added an example for more clarity :) – ItachiUchiha Apr 30 '15 at 18:27
-
Thanks, but for some reason line break (\n) isn't working. It just appends "\n" – Josh Beaver Apr 30 '15 at 18:40
-
I guess you are trying it in fxml. I have added a FXML example as well. – ItachiUchiha Apr 30 '15 at 18:41
-
Is it possible to add more Text Nodes after creation of the TextFlow? – Essej Dec 08 '16 at 13:59
-
@Baxtex Of course ;) You can use `getChildren()` on the TextFlow to add new Text nodes. – ItachiUchiha Dec 09 '16 at 06:50