the title already describes my problem. I want to color single letters or sequences of letters in a JFX Button but not the whole text. I found a solution for swing components Is it possible to change the text color in a string to multiple colors in Java? but not for javafx yet. Can anyone help me plz?
Asked
Active
Viewed 1,539 times
2 Answers
4
Check this out
public class ColoredButtonTextDemo extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
HBox coloredTextBox = HBoxBuilder.create().spacing(0).children(
LabelBuilder.create().text("Say ").textFill(Color.YELLOW).build(),
LabelBuilder.create().text("'").textFill(Color.DARKBLUE).build(),
LabelBuilder.create().text("Hell").textFill(Color.RED).build(),
LabelBuilder.create().text("o ").textFill(Color.GREEN).build(),
LabelBuilder.create().text("W").textFill(Color.BLUE).build(),
LabelBuilder.create().text("orld!").textFill(Color.DARKMAGENTA).build(),
LabelBuilder.create().text("'").textFill(Color.DARKBLUE).build()//
).build();
btn.setGraphic(coloredTextBox);
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output

Uluk Biy
- 48,655
- 13
- 146
- 153
1
This is just the FXML form of Uluk Biy's answer:
<Button>
<graphic>
<HBox spacing="0.0">
<Label text="Colors " style="-fx-text-fill: yellow; -fx-background-color: #1156cf;" />
<Label text="are " style="-fx-text-fill: red; -fx-background-color: #11cf56;" />
<Label text="cool!" style="-fx-text-fill: blue; -fx-background-color: #cf1156;" />
</HBox>
</graphic>
</Button>
...and yes, I love answering 7 years old questions. ;-)

tomorrow
- 1,260
- 1
- 14
- 26