Skip to content

Instantly share code, notes, and snippets.

@navopw
Created March 10, 2017 18:51
Show Gist options
  • Save navopw/4e7d37ae0aea905e88ebb9dfabb0665c to your computer and use it in GitHub Desktop.
Save navopw/4e7d37ae0aea905e88ebb9dfabb0665c to your computer and use it in GitHub Desktop.
DirectoryChooser - Java 8 Consumer Style
package de.navo.anything;
import java.awt.EventQueue;
import java.io.File;
import java.util.function.Consumer;
import javax.swing.JFileChooser;
public class DirectoryChooser {
/**
* The shortest way to handle a file selection with Java 8
* @param callback A callback with the chosen file, null when aborted selecting.
*/
public static void open(Consumer<File> callback) {
EventQueue.invokeLater(() -> {
JFileChooser filechooser = new JFileChooser();
filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (filechooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
callback.accept(filechooser.getSelectedFile());
} else {
callback.accept(null);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment