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!!
thanks.
ReplyDeleteThanks for the code. Works great!
ReplyDeletebut 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++)
Good snipet! Thanks for it.
ReplyDeleteI 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.
Thanks for pointing the mistake.
ReplyDeleteI have corrected it in the post now.
Also I will surely try to use a code formatter to make the code look better.