Search code examples
javafxcontextmenutransparencyshapes

JavaFX Context Menu stops Parent's Transparent Background


So, I've been programming an analog clock in JavaFX and have gotten the base functionality down. Now, I'm trying to add a drop-down menu when I click a custom button (triangle made with a Polygon). So far it all works fine, except the fact that the background of my StackPane is white when I try to add a ContextMenu either before or after clicking the button. So far Transparency has been fine up until now. Here's some pictures of the issue.

This is what it should look like (you can see my wallpaper because of the transparent window, as it should be.) enter image description here

After I press the button for the drop down menu, the background changes. enter image description here


Solution

  • JavaFX controls are styled by CSS. The first time you create a control, the default user agent stylesheet (modena.css) is loaded and the styles defined in it are applied to the scene graph. Other JavaFX node classes, such as shapes, image views, and layout panes, do not enforce CSS loading (this is to enhance performance for graphically-intensive applications that do not need CSS).

    So it sounds as though the context menu is the first control you create: when you create and display it, it will apply the default CSS to the scene. The default background color for the root pane is a non-transparent color, so while your Scene and Stage may be transparent, once the CSS is applied the scene's content is not.

    The fix is to specify transparency for the root pane:

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

    or the equivalent in an external stylesheet.