Search code examples
javacssjavafxtexttextflow

How to display white text with a black background?


I am trying to figure out why my text isn't being displayed here. I assume it isn't being colored white, and simply doesn't show up against the black background. So, I'm trying to figure out why the background is being colored black, but the text isn't being shown.

I am using JavaFX 12.

How can I color the letters white?

public class MCVE extends Application {

private static Stage gameStage = new Stage();

@Override
public void start(Stage primaryStage) {

   gameStage.setScene(new Scene(createScreen(), 1280.0, 800.0));

   // adjust window settings.
   gameStage.setTitle("my game");
   gameStage.setResizable(false);

   gameStage.show();
}

private Pane createScreen() {

   Text welcome = new Text("Welcome,");
   welcome.setFont(new Font("Old_Style", 22.0));
   welcome.setStyle("-fx-text-fill: whitesmoke");

   Text toMyGame = new Text(" to my game.");
   toMyGame.setFont(new Font("System", 14.0));
   toMyGame.setStyle("-fx-text-fill: whitesmoke");

   TextFlow tf = createTextFlow();
   ObservableList list = tf.getChildren();

   list.addAll(welcome, toMyGame);

   return tf;
}

private TextFlow createTextFlow() {

   String style = "-fx-background-color: black;";
   style += " -fx-text-fill: whitesmoke;";

   TextFlow tf = new TextFlow();
   tf.setStyle(style);

   return tf;
}

}

Solution

  • -fx-text-fill is a CSS property of Labeled, not Text. Text is a type of shape, and Shape supports -fx-fill rather than -fx-text-fill.

    Changing every occurrence of -fx-text-fill to -fx-fill should give you the appearance you want.