【JavaSwing】Swing界面风格开发

  • 格式:pdf
  • 大小:77.17 KB
  • 文档页数:2

【JavaSwing】Swing界⾯风格开发

JAVA的界⾯编程,有SWT,Swing组件都可以⽀持界⾯开发。此处使⽤JAVA原⽣的Swing组件开发,介绍如何定制系统主题。

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执⾏结果如下:

批注: UIManager.getCrossPaltformLookAndFeelClassName()执⾏结果,直接获取跨平台外观,返回的是外观类名字

批注: UIManager.getSystemLookAndFeelClassName()执⾏结果,获得系统的外观类名字

javax.swing.plaf.metal.MetalLookAndFeel javax.swing.plaf.nimbus.NimbusLookAndFeelcom.sun.java.swing.plaf.motif.MotifLookAndFeelcom.sun.java.swing.plaf.windows.WindowsLookAndFeel

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");

}

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