Here you can find the source of chooseOpenFile(String dir, String fileName, String fileNameExtension, Component parent)
Parameter | Description |
---|---|
dir | The directory from which a file will be selected. |
fileName | The initial file name that is prompted in the file field. |
fileNameExtension | The desired file extension. |
parent | The parent component that makes the call. |
null
otherwise.
public static File chooseOpenFile(String dir, String fileName, String fileNameExtension, Component parent)
//package com.java2s; //License from project: Open Source License import java.awt.Component; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; public class Main { /**// w w w . j a v a 2 s. co m * Opens a file chooser and returns the selected file if available. * * @param dir The directory from which a file will be selected. * @param fileName The initial file name that is prompted in the file field. * @param fileNameExtension The desired file extension. * @param parent The parent component that makes the call. * * @return An instance of {@link File} if the selection is successful, <code>null</code> otherwise. */ public static File chooseOpenFile(String dir, String fileName, String fileNameExtension, Component parent) { JFileChooser chooser = new JFileChooser(); File selectedFile = null; File fileDir = null; // if dir is not specified or the dir doesn't exist, use the current directory if (dir == null) { fileDir = new File("."); } else { fileDir = new File(dir); } if (!fileDir.exists()) { fileDir = new File("."); } chooser.setCurrentDirectory(fileDir); if (fileName != null) { chooser.setSelectedFile(new java.io.File(fileName)); } if (fileNameExtension != null) { chooser.setFileFilter(new FileNameExtensionFilter(fileNameExtension + " file", fileNameExtension)); } chooser.setDialogTitle("Open File"); boolean isValid = true; do { int chooserState = chooser.showDialog(parent, "Ok"); if (chooserState == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile(); if (!selectedFile.exists()) { JOptionPane.showMessageDialog(parent, selectedFile.getName() + " does not exist. Please choose another file!", "File Not Found", JOptionPane.WARNING_MESSAGE); } else { isValid = false; } } else { return null; } } while (isValid); return selectedFile; } }