Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Part of path returned from Directories Only JFileChooser is sometimes duplicated

In my application, I want the user to be able to select a directory to store stuff in. I have a text field that I'm using to display the directory they've chosen. If they just click on a directory (don't browse it), everything is fine. However, if they double click on the directory and look inside it, the directory name is duplicated.

Ex. They're in the home directory, single click the folder Desktop...path returned is ~/Desktop. On the other hand, if they're in the home directory, double click the folder Desktop, and now are in the Desktop folder, path returned is ~/Desktop/Destkop.

Here's what I'm doing:

JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(this);

if (returnVal == JFileChooser.APPROVE_OPTION) {
    File f = chooser.getSelectedFile();
    loadField.setText(f.getPath());
}

I've also tried to do something like chooser.getCurrentDirectory() but that doesn't really work either.

Edit: Using Mac OS X, Java 1.6

like image 753
knt Avatar asked Oct 14 '22 15:10

knt


1 Answers

Seems to work for me.

import javax.swing.JFileChooser;

public class FChoose {
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = chooser.showOpenDialog(null);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                java.io.File f = chooser.getSelectedFile();
                System.err.println(f.getPath());
            }
        }});
    }
}

6u13 on Vista. Is there something strange about your setup or what you are doing?

If there's a specific bug in a Mac OS X implementation of Java, you may want to, say, check if the file exists and if not de-dupe the last to elements of the path.

like image 129
Tom Hawtin - tackline Avatar answered Oct 18 '22 09:10

Tom Hawtin - tackline