本程式通用調用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);//建立ButtonLookAndFeel[] 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; //觀感名}}