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