Java Swing ช่วยให้เราปรับแต่ง GUI โดยเปลี่ยน รูปลักษณ์ (L&F) . รูปลักษณ์กำหนดลักษณะทั่วไปของส่วนประกอบและความรู้สึกกำหนดพฤติกรรม L&F เป็นคลาสย่อยของ LookAndFeel ชั้นเรียนและ L&F แต่ละรายการจะถูกระบุโดยชื่อชั้นเรียนที่มีคุณสมบัติครบถ้วน . โดยค่าเริ่มต้น L&F จะถูกตั้งค่าเป็น Swing L&F ( Metal L&F)
ในการตั้งค่า L&F โดยทางโปรแกรม เราสามารถเรียกเมธอด setLookAndFeel () ของ UIManager ระดับ. ต้องเรียกใช้ 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();
}
} ผลลัพธ์


