Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to set a different look and feels to swing components in Java?
The Java Swing allows us to customize the GUI by changing the look and feel(L&F). The look defines the general appearance of components and the feel defines their behavior. L&Fs are subclasses of the LookAndFeel class and each L&F is identified by its fully qualified class name. By default, the L&F is set to the Swing L&F ( Metal L&F)
To set the L&F programmatically, we can call the method setLookAndFeel () of the UIManager class. The call to setLookAndFeel must be done before instantiating any Java Swing class, otherwise, the default Swing L&F will be loaded.
Syntax
public static void setLookAndFeel(LookAndFeel newLookAndFeel) throws UnsupportedLookAndFeelException
Example
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();
}
}
Output
Advertisements