import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
class MyPanel extends JPanel{
public MyPanel(){
UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
//for(UIManager.LookAndFeelInfo info : infos){
makeJButton(infos[0].getName(),"MetalLookAndFeel");
/*makeJButton()的第二个参数为什么不能这样写,而要写成“javax.swing.plaf.metal.MetalLookAndFeel”?
我把他路径import进去了,下面的UIManager.setLookAndFeel(plafName);参数是个Sring型的类名,为什么要
带路径进去?*/
System.out.println(infos[0].getName());
System.out.println(infos[0].getClassName());
//}
}
public void makeJButton(String name,final String plafName){
JButton button = new JButton(name);
add(button);
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
try{
UIManager.setLookAndFeel(plafName);
SwingUtilities.updateComponentTreeUI(MyPanel.this);
}catch(Exception e){
e.printStackTrace();
}
};
}
);
}
}
class MyFrame extends JFrame{
public MyFrame(){
setTitle("ButtonTest");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
setLocation(200,300);
MyPanel mp = new MyPanel();
getContentPane().add(mp);
}
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 400;
}
public class ButtonTest{
public static void main(String args[]){
MyFrame mf = new MyFrame();
mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mf.setResizable(false);
mf.setVisible(true);
}
}
throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
UnsupportedLookAndFeelException
{
if ("javax.swing.plaf.metal.MetalLookAndFeel".equals(className)) {
// Avoid reflection for the common case of metal.
setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel());
}
else {
Class lnfClass = SwingUtilities.loadSystemClass(className);
setLookAndFeel((LookAndFeel)(lnfClass.newInstance()));
}
}其中SwingUtilities.loadSystemClass()方法static Class loadSystemClass(String className) throws ClassNotFoundException {
return Class.forName(className, true, Thread.currentThread().
getContextClassLoader());
}在Java中,forName方法需要完整的类限定名(即路径+类名)。
public static void setLookAndFeel(String className)
参数:
className - 指定实现外观的类名称的字符串 源码:public static void setLookAndFeel(String className)
throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
UnsupportedLookAndFeelException
{
if ("javax.swing.plaf.metal.MetalLookAndFeel".equals(className)) {
// Avoid reflection for the common case of metal.
setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel());
}
else {
Class lnfClass = SwingUtilities.loadSystemClass(className);
setLookAndFeel((LookAndFeel)(lnfClass.newInstance()));
}
}
而源码里有。这是为什么呢?难道我的API版本的问题?
throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
……