问题描述
介绍
我必须使用 NetBeans 平台和 JavaFX 11 对胖客户端进行编程。其中一项要求是为应用程序提供默认的深色主题。因此,如果应用程序的用户按下深色模式按钮,则应用程序的 GUI 必须使用深色主题。
问题
虽然我很清楚如何设置 JFX 组件的样式(通过 CSS 文件),但 CSS 文件对 NetBeans 平台的组件(如菜单栏)没有影响,因为它们是基于 Swing 的。例如,场景对象内的 JavaFX 组件采用深色样式,但 NetBeans 菜单栏仍然浅色。
问题
如何以编程方式更改 NetBeans 平台组件的样式(就像您在 Web 开发中使用 CSS 或在 JavaFX 中使用 CSS 支持所做的那样)?
解决方法
为了完整起见,我添加了解决我的问题的代码片段:
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,它看起来不错。
为了使用它,您需要在 validate()
子类的 ModuleInstall
方法中添加以下代码,以便在启动过程中尽早完成。
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 的(简单)方法。
有关更完整的示例代码,请查看我在 GitHub 上的应用程序 JJazzLab-X,位于 UISettings
Netbeans 模块中。