设置textArea中每个字符的背景颜色

Setting background color of each character in textArea

我是 JavaFX 的新手。我想在我的 TextArea 中执行下图所示的操作。我认为可以使用 Label 并设置它的背景颜色来完成。但是怎么办?

可以通过将 Label 放入某个布局容器中来完成,比如 HBox:

private final Random random = new Random();

private final Color[] colors =
{
    Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW
};


@Override
public void start( final Stage primaryStage )
{
    HBox hbox = new HBox();
    String str = "my-string-val";
    for ( String s : str.split( "" ) )
    {
        Label l = new Label( s );
        l.setBorder( new Border( new BorderStroke( Color.BLACK, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT ) ) );
        l.setBackground( new Background( new BackgroundFill( colors[random.nextInt( colors.length )], CornerRadii.EMPTY, Insets.EMPTY ) ) );
        l.setPrefWidth( 20 );
        l.setAlignment( Pos.CENTER );
        l.setFont( font( "Arial", FontWeight.BOLD, 16 ) );
        hbox.getChildren().add( l );
    }

    final Scene scene = new Scene( hbox, 800, 600 );
    primaryStage.setScene( scene );
    primaryStage.show();

}