
Java
You can change the current LnF by invoking:
UIManager.setLookAndFeel(lookAndFeel);
Probably the most useful invocation of this method uses the UIManager class to figure out what the underlying operating system is, and to use the default LnF for your program:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
This will make programs run on a Windows machine look like a Windows application, programs run on a Mac look like a Mac application, etc.
Another useful function is the UIManager.getInstalledLookAndFeels(), which will return an array of all available LnFs.
Below is a simple sample program which will demonstrate these methods.
Two things to take note of:
# Once you change the look and feel, you need to call the updateUI method on all JComponents. The good people at Sun recommend calling SwingUtilities.updateComponentTreeUI(Component). If you call this on your top level components (main frame/window), it should update all components contained within it. # UIManager.setLookAndFeel can throw a lot of exceptions. Be prepared to have a large try-catch block (or a throws clause) everywhere you set the LnF.
try {
// Start off with the system default LnF
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// Ugly, ugly try-catch block if you catch each type individually.
} catch (final ClassNotFoundException ex) {
} catch (final InstantiationException ex) {
} catch (final IllegalAccessException ex) {
} catch (final UnsupportedLookAndFeelException ex) {
} catch (final ClassCastException ex) {
}
// Create our frame
final JFrame frame = new JFrame("LnF Test Frame");
// Set up our simple panel
final JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
// Set up a button for each installed LookAndFeel.
// When a button is pressed, the LnF will change.
for (final LookAndFeelInfo lnfInfo : UIManager.getInstalledLookAndFeels()) {
final String lnfName = lnfInfo.getName();
final String lnfClassName = lnfInfo.getClassName();
final JButton button = new JButton(lnfName);
button.addActionListener(new ActionListener() {
// Here's where we change and update the LnF
public final void actionPerformed(final ActionEvent ev) {
try {
UIManager.setLookAndFeel(lnfClassName);
SwingUtilities.updateComponentTreeUI(frame);
} catch (final Exception ex) {
}
}
});
panel.add(button);
}
// Set up and display our frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// (adding a scroll panel just to see some more components)
frame.setContentPane(new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
frame.setSize(300, 300);
frame.setVisible(true);
Copyright © 2026 eLLeNow.com All Rights Reserved.