Friday, June 29, 2007

HOWTO: ensure correct JAVA Look and Feel at Program Startup

Overview
Lets face it, the default Java Look and Feel kind of sucks. It looks ok but when you have it next to a native app, it sticks out. Fortunately, the guys at SUN have made it easy to setup your JAVA program to automatically use the system look and feel.

Technique
During init of your GUI, simply add the following code. I like putting it in my constructor for the FORM.


try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);

} catch(Exception ex) {
ex.printStackTrace();
} // end-try-catch

What will happen is that the UIManager will set the look and feel using the System Look and Feel.

Last Thoughts
Using this simple snippet, you can make your JAVA program look more like a native application.

5 comments:

Xavier said...
This comment has been removed by the author.
Xavier said...

Yes it is really a good way to make the java application look better.

Actually we can use different look and feel to make our software more special, www.easynth.com provides a good solution for this.

Anonymous said...

Good for people to know.

Unknown said...

Thanks uuklanger!

I have a basic question for a laf expert: is it possible to have multiple look and feels in one app? here's my problem, my app uses laf A and I want a popup that displays a JFrame to keep its original look and feel, Thanks a lot

uuklanger said...

I have not tried it personally but I would suspect it is possible. Best way see is to pass something other then "this" to the

SwingUtilities.updateComponentTreeUI(this);

My guess is that the Swing component and its children will get whatever L&F you choose.

If I get a chance I will test it out. Also, if you have not tried Nimbus in Java 6u10 you should. It is very nice looking. Just be sure that you handle any exceptions if the L&F is not available for an end user.

http://blogs.sun.com/CoreJavaTechTips/entry/swingset3_nimbus_and_java_se

May help you get there.