Swing通過以下方式實現(xiàn)觀感:將JComponent分離成兩個獨立的類,一個JComponent子類,一個ComponentUI子類。ComponentUI子類在swing中有很多叫法:"the UI," "component UI," "UI delegate," "look and feel delegate"。
每個L&F都必須為ComponentUI提供具體實現(xiàn)的子類。
1、可獲得的L&F
(1)CrossPlatformLookAndFeel:Java l&f,即在各個平臺上的效果相同,這是默認的觀感,是JAVA API javax.swing.plaf.metal的一部分。
(2)SystemLookAndFeel:觀感依賴于本地系統(tǒng)。
(3)Synth:使用XML自定義觀感。
(4)Multiplexing:同時采用多個觀感。
SystemL&F 在以下包中:
com.sun.java.swing.plaf.gtk.GTKLookAndFeel
com.sun.java.swing.plaf.motif.MotifLookAndFeel
com.sun.java.swing.plaf.windows.WindowsLookAndFeel
2、通過程序設(shè)置觀感
設(shè)置觀感最好在應(yīng)用的第一步完成,通過UIManager來設(shè)置L&F,
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
3、通過命令行設(shè)置觀感
java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel MyApp
java -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel MyApp
4、通過swing.properties 設(shè)置觀感
# Swing properties
swing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel
5、如何選擇觀感
(1)程序通過setL&F方法顯示設(shè)置觀感;
(2)如無則使用swing.defaultlaf定義的觀感;如同時在命令行中設(shè)置觀感,命令行優(yōu)先;
(3)最后,使用JAVA L&F。
6、修改觀感
但應(yīng)用GUI已經(jīng)顯示后,仍然可以修改觀感。
UIManager.setLookAndFeel(lnfName);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
7、主題(Theme)
主題可以用來快速改變組件上文字的風格和顏色。每個L&F都有自己獨立的主題:
if (LOOKANDFEEL.equals("Metal")) {
if (THEME.equals("DefaultMetal"))
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
else if (THEME.equals("Ocean"))
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
else
MetalLookAndFeel.setCurrentTheme(new TestTheme());
UIManager.setLookAndFeel(new MetalLookAndFeel());
}