基於AWT、Swing的GUI程式 – 改變觀感

來源:互聯網
上載者:User

本程式通用調用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; //觀感名}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.