Generating Large Text With Different Styles - JavaFX FXML

In the fxml class of my JavaFx application, I want to add a large amount of text using minimal components (instead of adding multiple labels per line). I would also like to create different text styles in one component. Which component should I use (like TextArea) and how will I create multiple styles inside it (using css).

+3


source to share


1 answer


Use TextFlow and add Text to it. You can create a separate text component with a 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>

      

+4


source







All Articles