Java: Open or choose a file with JFileChooser

Last updated at 04:38 PM on Tuesday 6th November, 2007 by Administrator.


Using the JFileChooser[java.sun.com] class:

File dir = new File("../some/directory");

JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(dir);
fileChooser.setDialogTitle("Open");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// Only allow the user to select one file
fileChooser.setMultiSelectionEnabled(false);

if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
  File openFile = fileChooser.getSelectedFile();
  // Do something with the file
}

fileChooser.showOpenDialog() takes a Component as its argument. This can be a (custom) component or a JFrame.

In topics:

GUI

Comments: