1.类代码如下
package com.junglesong.mvc.common.menu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* 程序风格菜单
* @author junglesong@gmail.com
*
*/
public class StyleMenu extends JMenu {
// 程序的主框架
final JFrame mainFrame;
/**
* 构造函数
* @param text:菜单条文字
* @param frame:程序的主框架
*/
public StyleMenu(String text,JFrame frame) {
super(text);
mainFrame=frame;
addSubMenuItems();
}
/**
* 添加下级菜单项
*
*/
private void addSubMenuItems() {
// 取得系统当前可用感观数组
UIManager.LookAndFeelInfo[] arr = UIManager
.getInstalledLookAndFeels();
ButtonGroup buttongroup = new ButtonGroup();
for (int i = 0; i < arr.length; i++) {
JRadioButtonMenuItem styleMitem = new JRadioButtonMenuItem(
arr[i].getName(), i == 0);
final String className = arr[i].getClassName();
// 添加下级菜单项的事件相应
styleMitem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(className);
SwingUtilities.updateComponentTreeUI(mainFrame);
} catch (Exception ex) {
System.out.println("Can't Change Lookandfeel Style to "
+ className);
}
}
});
buttongroup.add(styleMitem);
this.add(styleMitem);
}
}
}
2.用法如下
JMenuBar menubar = new JMenuBar();
mainFrame.setJMenuBar(menubar);
......
menubar.add(Box.createHorizontalGlue());
JMenu styleMenu = new StyleMenu("Syle", mainFrame);
menubar.add(styleMenu);
......
例图: