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).
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With