Saturday, June 20, 2009

How to set Nimbus as look and feel in Java GUI

Recently,in the Java SE Update N, Nimbus was provided as one of the bundled look and feels. It is a good looking L&F and if someone has worked in the new Solaris then one can understand what Nimbus is all about.
To use Nimbus in your Java application , the below code will work:-
try {

UIManager.setLookAndFeel( "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception e)
{

}
This is a straight way to use Nimbus, however the problem with this code is that though it will work now, its a possibility that in Java 7, this way of using Nimbus can create problem as the location of Nimbus L&F class can change.

So a better way of using Nimbus is to find all the installed L&Fs by using UIManager.getInstalledLookAndFeels() ,then check if Nimbus is present and then use the getClassName to invoke the L&F.

The below steps will make it clear:-

UIManager.LookAndFeelInfo plafinfo[] = UIManager.getInstalledLookAndFeels();
boolean nimbusfound=false;
int nimbusindex=0;

for (int look = 0; look < plafinfo.length; look++) {
if(plafinfo[look].getClassName().toLowerCase().contains("nimbus"))
{
nimbusfound=true;
nimbusindex=look;
}
}

try {

if(nimbusfound)
{
UIManager.setLookAndFeel(plafinfo[nimbusindex].getClassName());
}
else

UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());

}
catch(Exception e)
{
}

By making use of this code, we make sure that our application will be able to use the Nimbus L&F even if the location of Nimbus L&F class changes in future version of Java.
Hope you liked the above information!!

4 comments:

  1. Thanks for the code. Works great!

    but you've got an error in the for loop syntax:

    for (int look = 0, look < plafinfo.length; look++)

    the fist comma must be a semicolon:

    for (int look = 0; look < plafinfo.length; look++)

    ReplyDelete
  2. Good snipet! Thanks for it.

    I suggets you using a code formater-highlighter like GeSHi (http://qbnz.com/highlighter/) or similar. It will improve the look and feel of your java code posts.

    ReplyDelete
  3. Thanks for pointing the mistake.
    I have corrected it in the post now.

    Also I will surely try to use a code formatter to make the code look better.

    ReplyDelete

Write Your Comments..

Share this Page:-