2

I have a JFileChooser that opens in a specific directory and then allows the user to choose a directory within it (when selected w/ single-click and the OK button is pressed).

However, when the directory is double-clicked, the file chooser opens that directory instead of choosing it.

How can I either

  1. override the double-click to choose the directory
  2. disable navigation outside of the initial directory
  3. disable double-clicking?

I've tried overriding the isTraversable() method in FileView and FileSystemView which works to restrict the file chooser to a directory, however, it then does not show any items inside of said directory.

Here's the code I have right now:

JFileChooser fc = new JFileChooser(dir);

fc.setApproveButtonText("OK");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
fc.showOpenDialog(fileChooserDialog);
File file = fc.getSelectedFile();
if (file.getParent().equals(dir)) {
    //do something
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
eggplant
  • 91
  • 11
  • 1
    Sounds like you want the user to search for a directory, not for a file. You should use a `JDirectoryChooser`. – Jashaszun Aug 02 '13 at 19:44
  • There's no JDirectoryChooser in the API? – eggplant Aug 02 '13 at 20:08
  • Oh nvm... I just did a quick Google search for "JDirectoryChooser" and saw that it as the first result. I didn't click on it, and thus didn't notice that it wasn't in the official JDK. However, looking at [this SO question](http://stackoverflow.com/questions/10463903/using-jdirectorychooser-in-java-swing), it looks like the solution is to call this on your `JFileChooser`: `setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);`. – Jashaszun Aug 02 '13 at 20:29
  • Jashaszun: if you see in my code that I provided, I already tried that. Tim: I've seen that topic and like I stated above, it doesn't work. – eggplant Aug 02 '13 at 22:20

1 Answers1

2

You could modify the action map. I don't have a access to a compiler ATM so I can't test this out, but it should work .

JFileChooser chooser = new JFileChooser(".");  
ActionMap am = chooser.getActionMap();  
Action key = am.get("WHATEVER_THEACTIONAME_FOR_OPEN-DIR._IS") //I think it's "Open Folder";
key.setEnabled(false);

I will update this answer later when I have time and access to a compiler.

madth3
  • 7,275
  • 12
  • 50
  • 74
Skylion
  • 2,696
  • 26
  • 50