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

时间:2015-04-29 10:53:21

标签: javafx javafx-8

我是JavaFX的新手。我想在TextArea中执行类似下图中的操作。我认为可以使用Label完成它并设置它的背景颜色。但是如何?

image

1 个答案:

答案 0 :(得分:1)

可以将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();

}