JavaFX BorderPane 不会采用背景色

JavaFX BorderPane will not take on background colour

我正在尝试按照 Oracle 提供的教程自学基本的 JavaFX。

在 BorderPane 教程中 (https://docs.oracle.com/javafx/2/layout/builtin_layouts.htm) 它指定了背景颜色。

这是我的代码片段:

/**
 * This Method creates and defines a horizontal box with a button.
 */
public HBox addHorizontalBoxWithButton() {
    // set up horizontal box and button
    HBox hBox = new HBox();
    hBox.setPadding(new Insets(10, 10, 10, 10));
    hBox.setSpacing(10);
    hBox.setStyle("-fx-background-colour: #FFFFFF;");
    hBox.setAlignment(Pos.CENTER);
    Button startButton = new Button("CLICK ME");
    startButton.setPrefSize(100, 30);
    // set up a message
    Text message = new Text("Click the button to get started.");
    message.setId("message");

    hBox.getChildren().add(message);
    hBox.getChildren().add(startButton);

    return hBox;
}

我尝试了各种不同的背景颜色,none 效果不错。我在这里遗漏了什么吗?

此外,我使用的是 .css 文件,但它只会向 'message' 添加样式。

好的,我刚刚解决了这个问题。

我这样修改了我的代码:

/**
 * This Method creates and defines a horizontal box with a button.
 */
public HBox addHorizontalBoxWithButton() {
    // set up horizontal box and button
    HBox hBox = new HBox();
    hBox.setId("hBox");
    hBox.setPadding(new Insets(10, 10, 10, 10));
    hBox.setSpacing(10);
    // hBox.setStyle("-fx-background-colour: #FFFFFF;");
    hBox.setAlignment(Pos.CENTER);
    Button startButton = new Button("CLICK ME");
    startButton.setPrefSize(100, 30);
    // set up a message
    Text message = new Text("Click the button to get started.");
    message.setId("message");

    hBox.getChildren().add(message);
    hBox.getChildren().add(startButton);

    return hBox;
}

我将其添加到 .css 文件中:

#hBox {
-fx-background-color: linear-gradient(#04B45F, #81F79F);
}

原始代码的唯一问题是您的样式设置中有 "typo"(英语化?)。应该是

hBox.setStyle("-fx-background-color: #FFFFFF;");

不是

hBox.setStyle("-fx-background-colour: #FFFFFF;");

使用外部样式 sheet 和

#hbox {
    -fx-background-color: red ;
}

是比使用内联样式更好的解决方案。