如何在 Java 中为 Swing 组件设置不同的外观和感觉?
awtjavaobject oriented programmingprogrammingswing
Java Swing 允许我们通过更改外观和感觉 (L&F) 来自定义 GUI。外观定义组件的总体外观,感觉定义其行为。L&F 是 LookAndFeel 类的子类,每个 L&F 都由其完全限定类名标识。默认情况下,L&F 设置为 Swing L&F (Metal L&F)
要以编程方式设置 L&F,我们可以调用 UIManager 类的方法 setLookAndFeel () 。在实例化任何 Java Swing 类之前,必须调用 setLookAndFeel,否则将加载默认的 Swing L&F。
语法
public static void setLookAndFeel(LookAndFeel newLookAndFeel) throws UnsupportedLookAndFeelException
示例
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LookAndFeelTest extends JFrame implements ActionListener { private JRadioButton windows, metal, motif, ; private ButtonGroup bg; public LookAndFeelTest() { setTitle("Look And Feels"); windows = new JRadioButton("Windows"); windows.addActionListener(this); metal = new JRadioButton("Metal"); metal.addActionListener(this); motif = new JRadioButton("Motif"); motif.addActionListener(this); bg = new ButtonGroup(); bg.add(windows); bg.add(metal); bg.add(motif); setLayout(new FlowLayout()); add(windows); add(metal); add(motif); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } @Override public void actionPerformed(ActionEvent ae) { String LAF; if(ae.getSource() == windows) LAF = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; else if(ae.getSource() == metal) LAF = "javax.swing.plaf.metal.MetalLookAndFeel"; else LAF = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; try { UIManager.setLookAndFeel(LAF); SwingUtilities.updateComponentTreeUI(this); } catch (Exception e) { System.out.println("Error setting the LAF..." + e); } } public static void main(String args[]) { new LookAndFeelTest(); } }