Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Thiết lập Look and Feel cho Swing components trong Java

Look and Feel (L&F)

Swing cho phép thay đổi giao diện (Look) và hành vi (Feel) tại runtime. Mặc định là Metal (CrossPlatform). Các L&F có sẵn: Windows, Metal, Motif, Nimbus (từ Java 6u10), macOS, v.v.

Cách đổi L&F chương trình

  1. Gọi UIManager.setLookAndFeel(String className) trước tạo bất kỳ component Swing nào.
  2. Gọi SwingUtilities.updateComponentTreeUI(Component) để làm mới UI của cây component hiện có.

Ví dụ: Chọn L&F bằng Radio Button

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LookAndFeelDemo extends JFrame implements ActionListener {
    private JRadioButton windows, metal, motif;
    private ButtonGroup group;

    public LookAndFeelDemo() {
        setTitle("Look And Feel Demo");
        windows = new JRadioButton("Windows");
        metal = new JRadioButton("Metal");
        motif = new JRadioButton("Motif");

        windows.addActionListener(this);
        metal.addActionListener(this);
        motif.addActionListener(this);

        group = new ButtonGroup();
        group.add(windows);
        group.add(metal);
        group.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 e) {
        String lafClassName;
        if (e.getSource() == windows) {
            lafClassName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
        } else if (e.getSource() == metal) {
            lafClassName = "javax.swing.plaf.metal.MetalLookAndFeel";
        } else {
            lafClassName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
        }

        try {
            UIManager.setLookAndFeel(lafClassName);
            SwingUtilities.updateComponentTreeUI(this); // refresh UI
        } catch (Exception ex) {
            System.err.println("Lỗi set LAF: " + ex);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(LookAndFeelDemo::new);
    }
}

Kết quả

Giao diện thay đổi ngay lập tức khi chọn radio button khác.

Thiết lập Look and Feel cho Swing components trong Java Thiết lập Look and Feel cho Swing components trong Java Thiết lập Look and Feel cho Swing components trong Java

Lưu ý: Nimbus (modern) class name: javax.swing.plaf.nimbus.NimbusLookAndFeel. Một số L&F chỉ khả dụng trên OS tương ứng (Windows L&F chỉ chạy trên Windows).