在JAVA的GUI开发中,Swing组件使用的是默认的皮肤,我们可以通过设置观感器来更改默认的皮肤。
如图所示,这就是JAVA默认观感器(XP系统)现实的效果。这一篇博客将通过示例代码为大家演示如何更改默认的观感器。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
/**
* 观感器示例
*
* @author jianggujin
*
*/
public class LookAndFeelDemo extends JFrame implements ActionListener
{
public LookAndFeelDemo()
{
super("SwingDemo");
JMenuBar menuBar = new JMenuBar();
JMenu skin = new JMenu("皮肤");
// 获得所有已安装观感器
LookAndFeelInfo[] lookAndFeelInfos = UIManager.getInstalledLookAndFeels();
// 遍历观感器并添加菜单项
for (LookAndFeelInfo lookAndFeelInfo : lookAndFeelInfos)
{
JMenuItem item = new JMenuItem(lookAndFeelInfo.getName());
item.setActionCommand(lookAndFeelInfo.getClassName());
item.addActionListener(this);
skin.add(item);
}
menuBar.add(skin);
setJMenuBar(menuBar);
JPanel root = new JPanel();
root.add(new JButton("我是JButton"));
root.add(new JToggleButton("我是JToggleButton"));
root.add(new JLabel("我是JLabel"));
root.add(new JCheckBox("我是JCheckBox"));
root.add(new JRadioButton("我是JRadioButton"));
root.add(new JTextField("我是JTextField"));
root.add(new JPasswordField("我是JPasswordField"));
root.add(new JTextArea("我是JTextArea"));
add(root);
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new LookAndFeelDemo();
}
@Override
public void actionPerformed(ActionEvent e)
{
JMenuItem item = (JMenuItem) e.getSource();
try
{
UIManager.setLookAndFeel(item.getActionCommand());
SwingUtilities.updateComponentTreeUI(this);
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
}
运行效果:
时间: 2024-10-29 07:39:01