java程序的界面编程详解
在Java中可以为程序自定义程序界面选择Windows、Unix、Java或Macintosh外观。甚至可以在程序运行时让用户自由的选择外观。
UIManager和SwingUtilities类
UIManager类保留了当前外观的信息,而SwingUtilities提供了几种实用的方法,尤其是UIManager类提供的静态方法setLookAndFeel。
一般的“界面”类如下:
javax.swing.plaf.metal.MetalLookAndFeel;
com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
com.sun.java.swing.plaf.motif.MotifLookAndFeel;
可以来创建以下界面:
1:Java界面
2:Unix界面
3:与操作系统和谐的界面
4:跨平台的界面
定义Java的界面:
try
{
String style = "javax.swing.plaf.metal.MetalLookAndFeel";
UIManager.setLookAndFeel(style);
}
catch (Exception e)
{
System.err.println("Exception: " + e);
}
定义与Unix界面:
try
{
String style = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
UIManager.setLookAndFeel(style);
}
catch (Exception e)
{
System.err.println("Exception: " + e);
}
定义与操作系统和谐的界面:
try
{
String style = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(style);
}
catch (Exception e)
{
System.err.println("Exception: " + e);
}
定义类似跨平台的界面:
try
{
String style = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(style);
}
catch (Exception e)
{
System.err.println("Exception: " + e);
}
下面是一段完整的换界面的代码:
package WindowStyle; import javax.swing.*; import java.awt.FlowLayout; import java.awt.Container; import java.awt.event.*; public class windowstyle extends JFrame implements ActionListener { private JButton windLook = new JButton("Windows"); private JButton unixLook = new JButton("Unix"); private JButton javaLook = new JButton("Java"); private JLabel label= new JLabel("FlySky Young"); private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } public windowstyle() { super("JFrame with Buttons"); Container content = getContentPane(); content.setLayout(new FlowLayout()); content.add(label); content.add(windLook); content.add(unixLook); content.add(javaLook); //添加按钮监听事件 windLook.addActionListener(this); unixLook.addActionListener(this); javaLook.addActionListener(this); validate(); pack(); setVisible(true); } public void actionPerformed(ActionEvent ae) { String style = "javax.swing.plaf.metal.MetalLookAndFeel"; if (ae.getSource() == windLook) { style = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; } else if (ae.getSource() == unixLook) { style = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; } try { UIManager.setLookAndFeel(style); SwingUtilities.updateComponentTreeUI(this); pack(); } catch (Exception e) { System.err.println("Exception: " + e); } } public static void main(String args[]) { windowstyle style = new windowstyle(); } }