Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a large body of text with different styles - JavaFX FXML

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).

like image 330
Josh Beaver Avatar asked Feb 10 '23 06:02

Josh Beaver


1 Answers

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

enter image description here

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="&#10;&#10;First Text" />
      <Text strokeType="OUTSIDE" strokeWidth="0.0" style="-fx-font-size: 30; -fx-fill: goldenrod;" text="&#10;&#10;Second Text" />
   </children>
</TextFlow>
like image 132
ItachiUchiha Avatar answered Feb 15 '23 13:02

ItachiUchiha