Swing 具有可插拔外观的概念。其中一些外观和感觉模仿了 Windows、GTK+ 等原生组件的外观。即使在 Windows 上,也有两种不同的外观和感觉——我认为是 Classic 和 Vista。也许您在两个系统上使用不同的操作系统和一个自动设置外观和感觉的 GUI 设计器。然而,大多数人不会——默认外观和感觉 Metal(Java 1.6.10 之前)和 Nimbus 在每个操作系统上看起来都一样。
// build the look and feel section
final LookAndFeelInfo[] lookAndFeelInfos = UIManager.getInstalledLookAndFeels();
List<String> lookAndFeelNames = new ArrayList<String>();
lookAndFeelNames.add("System");
for (LookAndFeelInfo lookAndFeelInfo : lookAndFeelInfos) {
if (!lookAndFeelInfo.getName().equals("CDE/Motif")) {
lookAndFeelNames.add(lookAndFeelInfo.getName());
}
}
if (selectedLookAndFeel.equals("System")) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SpellbookFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SpellbookFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SpellbookFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SpellbookFrame.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
for (LookAndFeelInfo lookAndFeelInfo : lookAndFeelInfos) {
if (lookAndFeelInfo.getName().equals(selectedLookAndFeel)) {
try {
UIManager.setLookAndFeel(lookAndFeelInfo.getClassName());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
}
}
}
SwingUtilities.updateComponentTreeUI(tabbedPane);
SwingUtilities.updateComponentTreeUI(parent);
代码的第一部分构建一个可用外观名称的列表,第二部分在其中一个被选中时进行操作。但是,由于您希望始终使用相同的 laf,您可以使用以下内容:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");