繁体   English   中英

NetBeans 平台:如何以编程方式设置基于 Swing 的 GUI 组件的样式?

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

介绍

我必须使用 NetBeans 平台和 JavaFX 11 编写胖客户端。其中一个要求是为应用程序提供默认和深色主题。 因此,如果应用程序的用户按下暗模式按钮,则应用程序的 GUI 必须使用暗主题。

问题

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. 例如,场景 object 中的 JavaFX 组件具有深色样式,但 NetBeans 菜单栏仍然是浅色的。

问题

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)?

为了完整起见,我添加了解决我的问题的代码片段:

    private void toggleLookAndFeel() {
        final boolean darkModeEnabled = UIManager.getLookAndFeel().getName().equals("Flat Dark");
        final String darkLookAndFeel = "com.formdev.flatlaf.FlatDarkLaf";
        final String defaultLookAndFeel = UIManager.getSystemLookAndFeelClassName();
        try {
            if (darkModeEnabled) {
                // set laf of swing components
                UIManager.setLookAndFeel(defaultLookAndFeel);
                // use default css file for javafx components
                this.fxPanel.getScene().getStylesheets().remove(0);
            } else {
                // set laf of swing components
                UIManager.setLookAndFeel(darkLookAndFeel);
                // use app.css file for javafx components
                this.fxPanel.getScene().getStylesheets().add(0, getClass().getResource("app.css").toExternalForm());
            }
        } catch (IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        triggerSwingComponentUpdate();
    }

    private static void triggerSwingComponentUpdate() {
        SwingUtilities.invokeLater(() -> {
            for (final Window w : Window.getWindows()) {
                SwingUtilities.updateComponentTreeUI(w);
            }
        });
    }

平台中有一个嵌入式暗 LAF(至少在我使用的 NB12 中),称为 FlatDarkLaf,看起来不错。

为了使用它,您需要在ModuleInstall子类的validate()方法中添加以下代码,以便在启动过程中很早就完成。

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

要切换回默认主题:

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

我不知道无需重新启动即可更改 LAF 的(简单)方法。

有关更完整的示例代码,请查看我的应用程序 JJazzLab-X on GitHub ,在UISettings Netbeans 模块中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM