MenuBar changes the background color of the scene (Java FX 8)

心已入冬 提交于 2021-01-19 09:05:47

问题


Why MenuBar changes the background color of the scene in this code sample? It should be blue but it is white.

package application;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.MenuBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root,400,400);
            scene.setFill(Color.rgb(0, 0, 255));

            primaryStage.setScene(scene);
            primaryStage.show();

            MenuBar menuBar = new MenuBar();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

回答1:


The white background you are seeing is the background of the BorderPane. This background color is set when the default stylesheet is loaded.

The reason that you only see this when the MenuBar is created is that CSS is only applied (unless you force it) when the first control is created. This is by design, to prevent the overhead of loading stylesheets and applying CSS for applications that don't need them (e.g. for games or simulations that manage all their own graphics). Since all controls are styled by CSS, just instantiating a control forces CSS to be applied.

The fix is to make the background of the BorderPane transparent.

Either

root.setStyle("-fx-background-color: transparent;");

or

root.setBackground(Background.EMPTY);

Of course, since you have to set the background of the root pane, you may as well set that to blue instead of setting the fill of the Scene:

        BorderPane root = new BorderPane();
        root.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, Insets.EMPTY)));
        Scene scene = new Scene(root,400,400);

Or, you can use an external style sheet:

.root {
    -fx-background-color: blue ;
}

Also see this related post and this OTN discussion.



来源:https://stackoverflow.com/questions/27336944/menubar-changes-the-background-color-of-the-scene-java-fx-8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!