Showing posts with label MAC OS. Show all posts
Showing posts with label MAC OS. Show all posts

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.

MAC OS X - InetAddress.getLocalHost() throws UnknownHostException

I am currently looking at some socket programming code which works in windows, but not in MAC OS X 10.7. I am using JDK 1.7. Previously this worked well in JDK 1.6.

The issue is with InetAddress.getLocalHost()
it throws java.net.UnknownHostException when I used with getHostAddress or getHostName.

The workaround is, edit host files.

Open Terminal and type the line shown below to edit in etc/hosts.
sudo nano /private/etc/hosts

Enter password.

In etc/hosts, (use arrow keys to move around) add a new line with  IP address <space> and hostname

Here, you can get the hostname by typing 'hostname' in terminal

To save control+o, then enter and to exit control+x

Now back in terminal, flush the cache by
dscacheutil -flushcache

Now, there should not be any error.

Sometimes you get both hostname and IP with getLocalHost(). Therefore, from getLocalhost() extract only the substring with the IP.

Steps are:

  1. First convert the inetAddress you get with getLocalHost to String. 
  2. Then get the substring with the IP (Original String will be in the form of <host_name>/<IP>) e.g. String ip_addr
  3. Convert back the IP substring to inetAddress to be used in Socket. InetAddress.getName(ip_addr)

More information @ http://java.net/jira/browse/MACOSX_PORT-564