Search code examples
javaswingjavafxnetbeansnetbeans-platform

NetBeans Platform: How to style the Swing based GUI components programmatically?


Intro

I have to program a fat client using NetBeans Platform and JavaFX 11. One of the requirements is to offer a default and dark theme for the application. So if the user of the application press the dark mode button, the application's GUI has to use the dark theme.

Problem

While it's obvious to me how to style the JFX components (via a CSS file), the CSS file doesn't have an impact on the NetBeans Platform's components like the menu bar, because they are Swing based. For instance the JavaFX components inside a scene object got a dark styling, but the NetBeans menu bar is still light.

Question

How its possible to change the style of NetBeans Platform's components programmatically (just as you would have done with CSS in web development or with the CSS support in JavaFX)?


Solution

  • There is an embedded dark LAF in the platform (at least in NB12 which I use) called FlatDarkLaf, it looks nice.

    In order to use it, you need to add the following code in the validate() method of a ModuleInstall subclass, so that it's done very early during the startup process.

    NbPreferences.root().node("laf").put("laf", "com.formdev.flatlaf.FlatDarkLaf");
    UIManager.installLookAndFeel(new UIManager.LookAndFeelInfo("FlatLaf Dark", latDarkLaf.class.getName()));  
    

    To switch back to the default theme:

    NbPreferences.root().node("laf").remove("laf");
    

    I'm not aware of a (simple) way of changing the LAF without restarting.

    For a more complete sample code have a look at my application JJazzLab-X on GitHub, in the UISettings Netbeans module.

    EDIT for Netbeans 12.5

    No need to call installLookAndFeel(), updating NbPreferences is enough.

    The module which updates NbPreferences should also have a dependency on the non-API Netbeans platform module FlatLaf Look and Feel.

    If your Netbeans platform app uses Netbeans branding (for ex. to customize icon and splash screen), it creates files such as frame.gif in your branding directory. But at runtime, if you run a dark theme like FlatDarkLaf, Netbeans will expect the icon to be named frame_dark.gif, so you should rename them. See the javadoc of ImageUtilities.loadImage() for more information.