So far we have discussed different swing components. Now I am going to show you here how to change the Look and Feel of components using Swing setLookAndFeel.

Swing setLookAndFeel Example:

Java provides UIManager class to manage the look and feel of swing components. The method setLookAndFeel is used to change the default look and feel.

MyFrameLAF.java
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

class MyFrameLAF extends JFrame implements ActionListener {
    JRadioButton windows, metal, motif;
    ButtonGroup Group;
    Container ContentPane;

    MyFrameLAF() {
        super("Look And Feel Demo");

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });

        windows = new JRadioButton("Windows");
        windows.addActionListener(this);
        
        metal = new JRadioButton("Metal");
        metal.addActionListener(this);
        
        motif = new JRadioButton("Motif");
        motif.addActionListener(this);

        Group = new ButtonGroup();

        Group.add(windows);
        Group.add(metal);
        Group.add(motif);

        ContentPane = getContentPane();
        ContentPane.setLayout(new FlowLayout());

        ContentPane.add(windows);
        ContentPane.add(metal);
        ContentPane.add(motif);

        pack();
        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);
        }
    }
}

class LookAndFeelDemo {
    public static void main(String args[]) {
        new MyFrameLAF();
    }
}

Output :

Basic Look and Feel :

Swing setLookAndFeel Basic

Windows Look and Feel :

Swing setLookAndFeel Windows

Metal Look and Feel :

Swing setLookAndFeel Metal

Motif Look and Feel :

Swing setLookAndFeel Motif

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment