JAVA的界面編程,有SWT,Swing組件都可以支持界面開發。
此處使用JAVA原生的Swing組件開發,介紹如何定制系統主題。
界面外觀的管理是由UIManager類來管理的。不同的系統上安裝的外觀不一樣 ,默認的是java的跨平台外觀。
1、獲取系統所有默認外觀
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyWindow1 extends JFrame { public static void main(String []agrs) { UIManager.LookAndFeelInfo []info = UIManager.getInstalledLookAndFeels() ; for(UIManager.LookAndFeelInfo tem:info) { System.out.println(tem.getClassName()); } } }
在本機windows執行結果如下:
javax.swing.plaf.metal.MetalLookAndFeel
批注: UIManager.getCrossPaltformLookAndFeelClassName()執行結果,直接獲取跨平台外觀,返回的是外觀類名字
javax.swing.plaf.nimbus.NimbusLookAndFeel
com.sun.java.swing.plaf.motif.MotifLookAndFeel
com.sun.java.swing.plaf.windows.WindowsLookAndFeel
批注: UIManager.getSystemLookAndFeelClassName()執行結果,獲得系統的外觀類名字
com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel
2、設置系統風格方法
UIManager.setLookAndFeel(new MetalLookAndFeel());
或
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
System.out.println("Substance Raven Graphite failed to initialize");
}
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
System.out.println("Substance Raven Graphite failed to initialize");
}
3、使用開源的 look$feel
常見有:Seaglass、Substance ,可以從網上下載對應的JAR包。
Substance 的使用樣例

try { UIManager.setLookAndFeel(new SubstanceLookAndFeel()); UIManager.put("swing.boldMetal", false); if (System.getProperty("substancelaf.useDecorations") == null)
{
// 使得標題欄和對話框跟隨外觀變化 JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); } System.setProperty("sun.awt.noerasebackground", "true"); //設置當前的主題風格,同樣還可以設置當前的按鈕形狀,水印風格等等 SubstanceLookAndFeel.setCurrentTheme(new SubstanceLightAquaTheme()); } catch (Exception e) { System.err.println("Oops! Something went wrong!"); }
4、添加水印背景
JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); try { SubstanceImageWatermark watermark = new SubstanceImageWatermark(LoginFrame.class.getResourceAsStream("/001.jpg")); watermark.setKind(ImageWatermarkKind.SCREEN_CENTER_SCALE); SubstanceSkin skin = new OfficeBlue2007Skin().withWatermark(watermark); //初始化有水印的皮膚 UIManager.setLookAndFeel(new SubstanceOfficeBlue2007LookAndFeel()); SubstanceLookAndFeel.setSkin(skin); //設置皮膚 } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex); }
代碼中 SubstanceLookAndFeel.setSkin(skin)必須要在 UIManager.setLookAndFeel(new SubstanceOfficeBlue2007LookAndFeel()); 這句的下面。
否則你看不到水印的效果
其中:SubstanceOfficeBlue2007LookAndFeel來自於開源的substance.jar