MenuBar更改场景的背景色(Java FX 8) [英] MenuBar changes the background color of the scene (Java FX 8)

查看:295
本文介绍了MenuBar更改场景的背景色(Java FX 8)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在此代码示例中MenuBar会更改场景的背景颜色?它应该是蓝色,但它是白色.

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);
    }
}

推荐答案

您看到的白色背景是BorderPane的背景.加载默认样式表时设置此背景颜色.

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

仅在创建MenuBar时看到此消息的原因是,仅在创建第一个控件时才应用CSS(除非您强制使用CSS).这是设计使然,以防止加载样式表并将CSS应用于不需要样式表的应用程序(例如,用于管理所有自己的图形的游戏或模拟)的开销.由于所有控件均由CSS设置样式,因此只需实例化控件即可强制应用CSS.

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.

解决方法是使BorderPane的背景透明.

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

任何一个

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

root.setBackground(Background.EMPTY);

当然,由于必须设置根窗格的背景,因此也可以将其设置为蓝色,而不是设置Scene的填充:

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 ;
}

另请参见此相关文章此OTN讨论.

这篇关于MenuBar更改场景的背景色(Java FX 8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆