Reputation: 31
Does someone know how to put two different colors on one sentence in a Java textfield (Java FX) (on a Label)? I am using CSS as well but would prefer to set it directly in the class.
Upvotes: 0
Views: 408
Reputation: 3824
Rich Text and Bidirectional Support
You can create several Text nodes and lay them out in a single text flow by using the TextFlow layout pane. The TextFlow object employs the text and font of each Text node but ignores the wrapping width and the x and y properties of its children. The TextFlow object uses its own width and text alignment to determine the location of each child. Example 39-12 shows three Text nodes that have different fonts and text laid out in a TextFlow pane.
String family = "Helvetica";
double size = 50;
TextFlow textFlow = new TextFlow();
textFlow.setLayoutX(40);
textFlow.setLayoutY(40);
// Red
Text text1 = new Text("Hello ");
text1.setFont(Font.font(family, size));
text1.setFill(Color.RED);
// Orange
Text text2 = new Text("Bold");
text2.setFill(Color.ORANGE);
text2.setFont(Font.font(family, FontWeight.BOLD, size));
// Green
Text text3 = new Text(" World");
text3.setFill(Color.GREEN);
text3.setFont(Font.font(family, FontPosture.ITALIC, size));
textFlow.getChildren().addAll(text1, text2, text3);
Group group = new Group(textFlow);
Scene scene = new Scene(group, 500, 150, Color.WHITE);
stage.setTitle("Hello Rich Text");
stage.setScene(scene);
stage.show();
https://docs.oracle.com/javase/8/javafx/user-interface-tutorial/text-settings.htm
The above example will produce Hello Bold World with Red, Orange, and Green (and with different styling). What you want cannot be done with TextField unless you want a strictly CSS solution. TextFlow is the way to go
Upvotes: 2
Reputation: 385
Use two different labels! Given that you seem to already know how to use them, just separate your text with labels and use those to set the color.
Upvotes: 0