Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java select a file location

Tags:

java

I'm not sure if this is even possible as I can't find anything about it after quite a few Google searches.

What I would like to do is on event open up a file dialog box and allow the user to select a folder and then store that folders full directory in a string. So if a user selected a folder in C:\Windows\Example the directory would be stored in String fileDir = C:\Windows\Example;

Does this make sense? I hope so as I'm struggeling to find the answer. I do apperciate the help, thanks in advance for looking and more thanks if you help me :)

like image 656
James Avatar asked Dec 22 '22 18:12

James


1 Answers

In swing you'll want a JFileChooser.

public String promptForFolder( Component parent )
{
    JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );

    if( fc.showOpenDialog( parent ) == JFileChooser.APPROVE_OPTION )
    {
        return fc.getSelectedFile().getAbsolutePath();
    }

    return null;
}

It can be a little awkward selecting folders from a user's perspective. I've watched a lot of folks struggle with it. If you have the time you may want to try my DirectoryChooser. Sorry the code is so crufty; I wrote it awhile back.

like image 104
Joseph Gordon Avatar answered Dec 24 '22 07:12

Joseph Gordon