Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ตั้งค่า Look and Feel ให้ Swing Components ใน Java

Java Swing ปรับแต่ง GUI ได้ด้วยการเปลี่ยน Look and Feel (L&F) Look = รูปลักษณ์, Feel = พฤติกรรม L&F เป็นคลาสย่อยของ LookAndFeel ระบุด้วย fully qualified class name ค่าเริ่มต้นคือ Metal L&F (Swing L&F)

ตั้งค่า L&F โดยโปรแกรม ใช้ UIManager.setLookAndFeel() ต้องเรียก ก่อนสร้างคอมโพเนนต์ Swing ใดๆ มิฉะนั้นจะโหลดค่าเริ่มต้น

ไวยากรณ์

public static void setLookAndFeel(LookAndFeel newLookAndFeel) throws UnsupportedLookAndFeelException

ตัวอย่าง: เปลี่ยน L&F ด้วย Radio Button

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); // รีเฟรช UI
        } catch (Exception e) {
            System.out.println("Error setting the LAF... " + e);
        }
    }
    
    public static void main(String args[]) {
        new LookAndFeelTest();
    }
}

ผลลัพธ์

ตั้งค่า Look and Feel ให้ Swing Components ใน Java

ตั้งค่า Look and Feel ให้ Swing Components ใน Java

ตั้งค่า Look and Feel ให้ Swing Components ใน Java

L&F มาตรฐาน: Windows, Metal (CrossPlatform), Motif (CDE), Nimbus (Java 6+), GTK+ (Linux)