创建按钮时,JavaFX 场景会丢失颜色

Car*_*and 5 javafx colors scene

谁能解释为什么我在 JavaFX 中创建按钮时我的场景会失去颜色?

以下代码有效,场景背景变为红色

@Override
public void start(Stage primaryStage){

    //Set Primary stage title and create a rootNode
    primaryStage.setTitle("Hello World");
    FlowPane rootNode = new FlowPane();

    //Create a scene and add it to the rootNode
    Scene myScene = new Scene(rootNode, 300, 200, Color.RED);

    //Add the scene to the stage
    primaryStage.setScene(myScene);

    //Show the stage
    primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)

但是,当我创建另一个控件时,例如下面示例中的按钮(我什至不必将其添加到流程窗格中),颜色将恢复为灰色。

@Override
public void start(Stage primaryStage){

    //Set Primary stage title and create a rootNode
    primaryStage.setTitle("Hello World");
    FlowPane rootNode = new FlowPane();

    //Create a scene and add it to the rootNode
    Scene myScene = new Scene(rootNode, 300, 200, Color.CORAL);

    Button newBtn = new Button();

    //Add the scene to the stage
    primaryStage.setScene(myScene);

    //Show the stage
    primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)

有谁知道这是为什么?我是否试图错误地更改背景颜色?

Mar*_*uin 0

TL;DR将 的背景颜色设置rootPane为所需的颜色或Color.TRANSPARENT

这是一个非常奇怪的案例。

当您最初创建该Button方法时initialize,会在 Button 的构造函数中调用该方法:

private void initialize() {
    getStyleClass().setAll(DEFAULT_STYLE_CLASS);
    setAccessibleRole(AccessibleRole.BUTTON);
    setMnemonicParsing(true);     // enable mnemonic auto-parsing by default
}
Run Code Online (Sandbox Code Playgroud)

我假设(但我不能 100% 确定地告诉你)这会将样式应用于应用程序中的元素(如本答案中所述,这是因为静态初始化程序),因为如果你创建一个Button(并且甚至不将其添加到你的应用程序中)rootNode)rootNode调用后会有背景primaryStage.show()。为了证明这一点,我修改了您的代码:

System.out.println("background: " + rootNode.getBackground());
Button newBtn = new Button();
primaryStage.setScene(myScene);
primaryStage.show();
System.out.println("background after showing scene: " + rootNode.getBackground());
Run Code Online (Sandbox Code Playgroud)

输出如下所示(背景颜色为灰色):

background: null
background after showing scene: javafx.scene.layout.Background@20c95282
Run Code Online (Sandbox Code Playgroud)

如果我删除按钮创建并再次运行它,背景颜色为红色,并且我有以下输出:

background: null
background after showing scene: null
Run Code Online (Sandbox Code Playgroud)

所以我建议您要么将背景颜色设置为rootNode,要么明确将 的背景颜色设置rootNode为透明(Color.TRANSPARENT)。两种解决方案都对我有用。

rootNode.setBackground(new Background(new BackgroundFill(Color.CORAL, null, null)));
Run Code Online (Sandbox Code Playgroud)