问题
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