swing ui主题_Swing开发实现不同显示风格切换(换肤)的方法

本文介绍了如何使用Swing开发用户界面时改变默认风格,使其变得更加美观。通过 javax.swing.UIManager 的 setLookAndFeel 方法,可以动态切换显示风格。提供了一个封装函数setUIStyle,接受显示风格字符串和目标组件,进行风格设置并更新组件树,以适应不同的系统环境。此功能简化了UI设计,提高了开发效率。

使用Swing开发用户界面时,你是否为Swing默认界面不够漂亮而烦恼呢,以前的办法是使用大量的图片来构建用户界面,这种方法虽然可以实现漂亮的效果,但是实现成本太高,不够实用。

自从Swing支持不同显示风格以后,我们也可以使用Swing快速地开发出漂亮的用户界面了,而且使用这种机制支持用户动态切换显示风格。Swing实现显示风格切换主要是通过javax.swing.UIManager类的静态成员方法setLookAndFeel实现的,该方法的原型如下:

public static void setLookAndFeel(String className)

throws ClassNotFoundException,

InstantiationException,

IllegalAccessException,

UnsupportedLookAndFeelException

Loads the LookAndFeel specified by the given class name, using the current thread's context class loader, and passes it to setLookAndFeel(LookAndFeel).

该方法接受一个字符串类型的className作为显示风格标识的输入参数。

为了使用方便,我们依然将这个独立功能封装在一个函数中,下面给出该函数的实现代码:

/**

* 设置显示风格

* @param strStyle

*/

public static void setUIStyle(String strStyle,Component target){

try {

UIManager.setLookAndFeel(strStyle);

if (target != null)

SwingUtilities.updateComponentTreeUI(target);

} catch (ClassNotFoundException e) {

new NormalException("显示风格类型不存在:"+e.getMessage(),e);

} catch (InstantiationException e) {

new NormalException("初始化显示风格失败:"+e.getMessage(),e);

} catch (IllegalAccessException e) {

new NormalException("连接显示风格失败:"+e.getMessage(),e);

} catch (UnsupportedLookAndFeelException e) {

new NormalException("当前系统不支持的显示风格:"+e.getMessage(),e);

}catch(IllegalStateException err){

new FatalException("载入显示风格错误:"+err.getMessage(),err);

}catch(NullPointerException err){

new FatalException("空指针错误:"+err.getMessage(),err);

}

}

该方法是一个静态方法,接受一个表示显示风格的字符串样式strStyle和需要设置显示风格的目标窗口target,在调用UIManager的静态成员方法setLookAndFell之后,还需要调用SwingUtilities的静态成员方法updateComponentTreeUI实现窗口的显示更新。该方法的原型即API说明如下:

public static void updateComponentTreeUI(Component c)

A simple minded look and feel change: ask each node in the tree to updateUI() -- that is, to initialize its UI property with the current look and feel.

【发表评论0条 】

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值