JavaFX 8 工具提示移除了舞台的透明度

JavaFX 8 tooltip removes transparency of stage

我很难弄清楚为什么我的透明舞台拒绝透明。最后我发现,它是由安装到 ImageView:

中的 Tooltip 引起的
ImageView imageViewIcon = new ImageView();
imageViewIcon.setFitWidth(70);
imageViewIcon.setFitHeight(70);
imageViewIcon.setPreserveRatio(false);
imageViewIcon.setImage(new Image("./next.png"));

Tooltip tooltip = new Tooltip("Tooltip!");
if (this.config.getShowTooltip("true")) {
    Tooltip.install(imageViewIcon, tooltip);
}

当我注释掉最后 4 行时,透明度按预期工作,但安装了 Tooltip 后,舞台背景呈灰色(例如默认的 window 背景)。虽然按钮的作用很明显,而且工具提示对于我的布局来说不是必需的,但如果有它就好了,只是给出一点提示...

有什么建议或解决方法吗?

解决方案

在场景的根节点上设置样式-fx-background-color: transparent

背景

Oracle JavaFX Forum post on the JavaFX Scene/Fill Color 中讨论了类似的行为。

来自 JavaFX CSS 功能的首席开发人员 David Grieve 的线程的相关评论:

This happens because modena.css sets the background color of the root node. Setting the style -fx-background-color: transparent on the root node of the scene is the solution.

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

Scene scene = new Scene(root, 600, 400, Color.BLACK); 

The default user agent stylesheet is loaded the first time a Control is instantiated. The reason for this is to avoid loading stylesheets and reduce CSS overhead in scene-graphs that contain nodes that don't use CSS.


The history behind it is that the designer of the modena theme felt that the controls looked better on this particular background color, which is a very light grey. Unfortunately, the Scene's background fill cannot be styled from CSS, so the style was set on the root node of the scene. There is an issue logged in JIRA to make Scene so that it can be styled by CSS (RT-31282)

The merit of loading in this way is to avoid css overhead in scene's that don't use controls. This would be typical of a splash screen, for example. Or maybe a game. This design choice was made a long time ago when CSS performance was a big issue, but it still makes sense for embedded devices.


对于您的问题,Tooltip 是一个控件,因此当您将它添加到场景时,它会隐式触发为场景加载默认 modena.css 样式表(设置场景根节点的背景为灰色,而不是在场景中没有控件时使用的空填充或透明填充)。要在场景中使用控件时为应用程序保留透明背景,需要明确将场景根节点背景设置为透明。


Sample code for a transparent stage:

//this is where the transparency is achieved:
//the three layers must be made transparent
//(i)  make the VBox transparent (the 4th parameter is the alpha)
root.setStyle("-fx-background-color: rgba(0, 0, 0, 0);");
//(ii) set the scene fill to transparent
scene.setFill(null);
//(iii) set the stage background to transparent
stage.initStyle(TRANSPARENT);