views:

734

answers:

3

I'm trying to generate a JFileChooser that has the Windows look-and-feel. I couldn't find a method to change it, so I created a base class that extends JFileChooser that changes the UI with the following code:

public FileChooser(){
  this(null);
}
public FileChooser(String path){
   super(path);
   try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

    } catch (Exception e) { System.err.println("Error: " + e.getMessage()); }

Then, in another class, I call

FileChooser chooser = new FileChooser(fileName);
int val = chooser.showOpenDialog(null);

but the dialog box that comes up has the Java look and feel. Any thoughts on how to change this? Is there a method of the JFileChooser class that I can use instead of this extended class?

Thank you!

+3  A: 

If you don't need to change the Look and Feel, could you try putting the UIManager.setLookAndFeel(..) line in the main method of your entry class?

That seems to work for me, though I am at a loss as to why it won't work the way you have set it upt.

Luhar
The problem was that I set the look-and-feel after I displayed the `JFileChooser`. I also didn't understand that I could change the UI for the whole thing at once. Thank you for the hint.
chama
+2  A: 

First, try running the code from the command line and specify the look and feel there to see that it can be applied.

 java -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel YourApp

If it does apply the correct look and feel then you can add the look and feel code to the program before you create the JFileChooser dialog. Lets say a simple program would look like this:

 public static void main(String[] args) {
try {

    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

} 
catch (Exception e) {
   // handle exception
}

JFileChooser chooser = new JFileChooser(); 
//etc
}
Vincent Ramdhanie
+1 for the command line option.
Luhar
A: 

The problem is that the Look & Feel was already selected for you when you called super(path).

From the Java Tutorial for Look and Feel:

Note: If you are going to set the L&F, you should do it as the very first step in your application. Otherwise you run the risk of initializing the Java L&F regardless of what L&F you've requested. This can happen inadvertently when a static field references a Swing class, which causes the L&F to be loaded. If no L&F has yet been specified, the default L&F for the JRE is loaded. For Sun's JRE the default is the Java L&F, for Apple's JRE the Apple L&F, and so forth.

To remedy, you should do this (explanation located here) - replace your try/catch block with this code:

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
this.pack();
Tim Drisdelle