Sunday, October 14, 2012

Issue - JFileChooser on Mac OS X

These days I am converting a java code written in a Windows system to MAC OS X Lion(10.7.X). Though we know java is platform independent, with MAC OS I am getting various issues. I am having JDK 1.7.

The current problem I am having is with JFileChooser. According to Oracle, file chooser GUI is used for navigating the file system, and then either choosing a file or directory from a list, or entering the name of a file or directory. To display a file chooser, you usually use the JFileChooser API to show a modal dialog containing the file chooser.

So what is the problem I am facing. I am unable to select files with JFileChooser, even if I had set the selection mode as FILES_AND_DIRECTORIES. Even if the files are shown, in file chooser window the file names appear in gray. Thus, even if a file is selected and clicked save, actually a file is not selected. The sample code segment is shown below.

Code...
JFileChooser chooser = new JFileChooser()chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );

I tried various options to solve it, but could not get it to work. :(

Found the solution!! You need to change the default Look and Feel (LAF or L&F) for MAC.

At the beginning you have to set to JAVA LAF.

try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch(Exception e) { System.out.println("Error setting Java LAF: " + e); }

It is working now. :) You can try to change into other LAFs and see how it appears.

2 comments:

  1. Thank you for this. My JFileChooser on my mac was never showing up before this but now it works perfectly.

    ReplyDelete