import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//顯示多種風格的窗口
public class LookAndFeelDemo extends JFrame {
public LookAndFeelDemo(){
super("多種風格的窗口"); //調用父類構造函數
Container container=getContentPane(); //得到容器
JMenu menuTheme=new JMenu("窗口風格"); //初始化菜單
JMenuItem itemNative=new JMenuItem("系統平台風格"); //初始化菜單項
JMenuItem itemMotif=new JMenuItem("Motif風格");
JMenuItem itemMetal=new JMenuItem("跨平台風格");
menuTheme.add(itemNative); //增加菜單項
menuTheme.add(itemMotif);
menuTheme.add(itemMetal);
itemNative.addActionListener(new ActionListener(){ //菜單項事件處理
public void actionPerformed(ActionEvent event){
changeLookAndFeel("Native"); //調用方法,改變窗口風格
}
});
itemMotif.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
changeLookAndFeel("Motif");
}
});
itemMetal.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
changeLookAndFeel("Metal");
}
});
JMenuBar menuBar=new JMenuBar(); //初始化菜單欄
menuBar.add(menuTheme); //增加菜單到菜單欄
setJMenuBar(menuBar); //設置菜單
JPanel panel=new JPanel(); //初始化一個JPanel
panel.setBorder(BorderFactory.createTitledBorder("組件樣式")); //設置邊界
panel.add(new JTextField("文本框:Look and feel測試 ")); //增加組件到panel上
panel.add(new JCheckBox("粗體"));
panel.add(new JCheckBox("斜體"));
panel.add(new JCheckBox("下劃線"));
panel.add(new JButton("確定"));
panel.add(new JButton("退出"));
container.add(panel); //增加panel到容器上
setSize(220,200); //設置窗口尺寸
setVisible(true); //設置窗口可見
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉窗口時退出程序
}
//改變窗口樣式
public void changeLookAndFeel(String type){
try{
if (type.equals("Native")) { //判斷來自於哪個菜單項
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //設置界面樣式
}
else if (type.equals("Motif")) {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
else if (type.equals("Metal")) {UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
}
javax.swing.SwingUtilities.updateComponentTreeUI(this); //更新界面
}
catch(Exception ex){ //捕捉錯誤
ex.printStackTrace(); //輸出錯誤
}
}
public static void main(String[] args){
new LookAndFeelDemo();
}
}