基于AWT、Swing的GUI程序 - 改变观感
本程序通用调用UIManager.getInstalledLookAndFeels()方法来获取本机已安装的所有观感,然后分别创建相应数量的Button,用来动态改变观感。
相关API :
static voidsetLookAndFeel(LookAndFeel newLookAndFeel)
设置观感
static voidupdateComponentTreeUI(Component c)
动态更新观感
执行效果:
![]()
代码:
static UIManager.LookAndFeelInfo[]getInstalledLookAndFeels()
获取本机已安装的所有观感
执行效果:
代码:
package cn.youthol;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main
{
	/**
	 * author bruce
	 */
	public static void main(String[] args)
	{
		EventQueue.invokeLater(new Runnable()
		{
			public void run()
			{
				MyFrame frame = new MyFrame("Change LookAndFeel");
				frame.setDefaultCloseOperation(MyFrame.EXIT_ON_CLOSE);
				frame.setVisible(true);
			}
		});
	}
}
/*
 * 框架窗口
 */
class MyFrame extends JFrame
{
	private JPanel btnPanel;
	
	/*
	 * 构造方法
	 */
	public MyFrame(String title)
	{
		//设置标题
		super(title);
		
		//设置大小
		setSize(800,600);
		
		//创建按钮面板
		btnPanel = new JPanel();
		add(btnPanel);
		
		//创建Button
		LookAndFeel[] names = getAllLookAndFeels();
		for(LookAndFeel name : names)
		{
			createButton(name.name,name.className);
		}
	}
	
	/*
	 * 得到所有观感
	 * LookAndFeel是自定义的类,用来存储观感信息
	 */
	private LookAndFeel[] getAllLookAndFeels()
	{
		UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
		
		LookAndFeel[] lafs = new LookAndFeel[infos.length];
		for(int i = 0 ; i < lafs.length ; ++i)
		{
			lafs[i] = new LookAndFeel();
		}
		for(int i = 0 ; i < lafs.length ; ++i)
		{
			System.out.println(i);
			lafs[i].className = infos[i].getClassName();
			lafs[i].name = infos[i].getName();
		}
		
		return lafs;
	}
	/*
	 * 创建Button
	 */
	private void createButton(String name,final String UIName)
	{
		JButton btn = new JButton(name);
		btnPanel.add(btn);
		
		//设置监听器
		btn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				//改变观感
				try
				{
					UIManager.setLookAndFeel(UIName);
					SwingUtilities.updateComponentTreeUI(MyFrame.this);
				}
				catch(Exception ex)
				{
					ex.printStackTrace();
				}
			}
		});
	}
	
	/*
	 * 内部类LookAndFeel
	 * 用来存储观感信息
	 */
	private class LookAndFeel
	{
		String className; //类名
		String name; //观感名
	}
}
                    
                
                
            
        
浙公网安备 33010602011771号