如何在 Java 中为 Swing 组件设置不同的外观和感觉?
Java Swing 使我们能够通过改变外观和感觉 (L&F)来定制 GUI。外观定义组件的一般外观,而感觉定义它们的行为。L&F 是LookAndFeel类的子类,每个 L&F 都由其完全限定类名来标识。默认情况下,L&F 设置为Swing L&F (Metal L&F)
要以编程方式设置 L&F,我们可以调用UIManager类的setLookAndFeel () 方法。setLookAndFeel 的调用必须在实例化任何 Java Swing 类之前执行,否则将加载默认的 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(); } }
输出
广告