Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
952 views
in Technique[技术] by (71.8m points)

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

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...