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