Java Code Examples for javax.swing.JFileChooser#getSelectedFiles()

The following examples show how to use javax.swing.JFileChooser#getSelectedFiles() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProductSetPanel.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
private static File[] getFilePath(Component component, String title) {

        File[] files = null;
        final File openDir = new File(SnapApp.getDefault().getPreferences().
                get(OpenProductAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, "."));
        final JFileChooser chooser = FileChooserFactory.getInstance().createFileChooser(openDir);
        chooser.setMultiSelectionEnabled(true);
        chooser.setDialogTitle(title);
        if (chooser.showDialog(component, "OK") == JFileChooser.APPROVE_OPTION) {
            files = chooser.getSelectedFiles();

            SnapApp.getDefault().getPreferences().
                    put(OpenProductAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, chooser.getCurrentDirectory().getAbsolutePath());
        }
        return files;
    }
 
Example 2
Source File: SignUI.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 6 votes vote down vote up
public static List<Data> showFileSelection() throws Exception{
    List<Data> ret = new ArrayList<Data>();
    
    JFileChooser jfc = new JFileChooser();
    jfc.setMultiSelectionEnabled(true);
    
    jfc.setDialogTitle("Choose the files to sign");
    SignUtils.playBeeps(1);
    if(jfc.showOpenDialog(null) != JFileChooser.APPROVE_OPTION)
        return null;
    
    File[] choosedFileList = jfc.getSelectedFiles();
    for(File file:choosedFileList){
        String id = file.getAbsolutePath();
        byte[] fileContent = IOUtils.readFile(file);
        ret.add(new Data(id, fileContent));
    }
    return ret;
}
 
Example 3
Source File: AttachmentView.java    From jdal with Apache License 2.0 6 votes vote down vote up
/**
 * Add Attachments from user selections
 */
private void addAttachment() {
	JFileChooser chooser = new JFileChooser();
	chooser.setMultiSelectionEnabled(true);

	if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(getPanel())) {
		File[] files = chooser.getSelectedFiles();
		List<Attachment> addList = new ArrayList<Attachment>(files.length);
		for (File file : files) {
			try {
				addList.add(new Attachment(file));
			} catch (IOException e) {
				JOptionPane.showMessageDialog(getPanel(), 
						getMessage("AttachmentView.cantReadFile") + " " + file.getName());
			}
		}
		ListListModel listModel = (ListListModel) attachments.getModel();
		listModel.addAll(addList);
	}
}
 
Example 4
Source File: FrmTextEditor.java    From MeteoInfo with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void doOpen_Groovy() {
    // TODO add your handling code here:          
    JFileChooser aDlg = new JFileChooser();
    aDlg.setMultiSelectionEnabled(true);
    aDlg.setAcceptAllFileFilterUsed(false);
    //File dir = new File(this._parent.getCurrentDataFolder());
    File dir = new File(System.getProperty("user.dir"));
    if (dir.isDirectory()) {
        aDlg.setCurrentDirectory(dir);
    }
    String[] fileExts = new String[]{"groovy"};
    GenericFileFilter mapFileFilter = new GenericFileFilter(fileExts, "Groovy File (*.groovy)");
    aDlg.setFileFilter(mapFileFilter);
    if (JFileChooser.APPROVE_OPTION == aDlg.showOpenDialog(this)) {
        File[] files = aDlg.getSelectedFiles();
        //this._parent.setCurrentDataFolder(files[0].getParent());
        System.setProperty("user.dir", files[0].getParent());
        this.openFiles(files);
    }
}
 
Example 5
Source File: FileNamesComponent.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
public void actionPerformed(ActionEvent e) {

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(true);
    if ((filters != null) && (filters.length > 0)) {
      for (FileFilter f : filters)
        fileChooser.addChoosableFileFilter(f);
      fileChooser.setFileFilter(filters[0]);

    }
    String currentPaths[] = txtFilename.getText().split("\n");
    if (currentPaths.length > 0) {
      File currentFile = new File(currentPaths[0].trim());
      File currentDir = currentFile.getParentFile();
      if (currentDir != null && currentDir.exists())
        fileChooser.setCurrentDirectory(currentDir);
    }

    int returnVal = fileChooser.showDialog(null, "Select files");

    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File selectedFiles[] = fileChooser.getSelectedFiles();
      setValue(selectedFiles);
    }
  }
 
Example 6
Source File: ReportingControlPanel.java    From VanetSim with GNU General Public License v3.0 6 votes vote down vote up
/**
 */

public void makejobs(){
	//begin with creation of new file
	JFileChooser fc = new JFileChooser();
	
	//set directory and ".log" filter
	fc.setMultiSelectionEnabled(true);
	fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
	fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
	
	int status = fc.showDialog(this, Messages.getString("EditLogControlPanel.approveButton"));
	
	if(status == JFileChooser.APPROVE_OPTION){
		File[] tmpFiles = fc.getSelectedFiles();
		
		
			for(File file:tmpFiles){
				//get log names
				System.out.println(file.getName() +":slow:standard:0.0:2.2:0.9:0.85:0.9:0.9:0.1:170.0:true:0:10000.0");

			}
	}
}
 
Example 7
Source File: LibraryStartVisualPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void browseLibraryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseLibraryButtonActionPerformed
    JFileChooser chooser = new JFileChooser(ModuleUISettings.getDefault().getLastChosenLibraryLocation());
    File[] olds = convertStringToFiles(txtLibrary.getText().trim());
    chooser.setSelectedFiles(olds);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(true);
    chooser.addChoosableFileFilter(new JarZipFilter());
    int ret = chooser.showDialog(this, getMessage("LBL_Select"));
    if (ret == JFileChooser.APPROVE_OPTION) {
        File[] files =  chooser.getSelectedFiles();
        if (files.length == 0) {
            return;
        }
        String path = "";
        for (int i = 0; i < files.length; i++) {
            path = path + files[i] + ( i == files.length - 1 ? "" : File.pathSeparator);
        }
        txtLibrary.setText(path);
        ModuleUISettings.getDefault().setLastChosenLibraryLocation(files[0].getParentFile().getAbsolutePath());
    }
}
 
Example 8
Source File: DisplayEntityFactory.java    From jaamsim with Apache License 2.0 6 votes vote down vote up
/**
 * Opens a FileDialog for selecting images to import.
 *
 * @param gui - the Control Panel.
 */
public static void importImages(GUIFrame gui) {

	// Create a file chooser
	final JFileChooser chooser = new JFileChooser(GUIFrame.getImageFolder());
	chooser.setMultiSelectionEnabled(true);

	// Set the file extension filters
	chooser.setAcceptAllFileFilterUsed(false);
	FileNameExtensionFilter[] imgFilters = FileInput.getFileNameExtensionFilters("Image",
			ImageModel.VALID_FILE_EXTENSIONS, ImageModel.VALID_FILE_DESCRIPTIONS);
	for (int i = 0; i < imgFilters.length; i++) {
		chooser.addChoosableFileFilter(imgFilters[i]);
	}
	chooser.setFileFilter(imgFilters[0]);

	// Show the file chooser and wait for selection
	int returnVal = chooser.showDialog(gui, "Import Images");

	// Create the selected graphics files
	if (returnVal == JFileChooser.APPROVE_OPTION) {
		File[] files = chooser.getSelectedFiles();
		GUIFrame.setImageFolder(files[0].getParent());
		DisplayEntityFactory.importImageFiles(files);
	}
}
 
Example 9
Source File: OutputPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void addOutputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addOutputActionPerformed
    JFileChooser chooser = new JFileChooser();
    FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
    chooser.setFileSelectionMode (JFileChooser.FILES_AND_DIRECTORIES);
    chooser.setMultiSelectionEnabled(true);
    if (lastChosenFile != null) {
        chooser.setSelectedFile(lastChosenFile);
    } else {
        File files[] = model.getBaseFolder().listFiles();
        if (files != null && files.length > 0) {
            chooser.setSelectedFile(files[0]);
        } else {
            chooser.setSelectedFile(model.getBaseFolder());
        }
    }
    chooser.setDialogTitle(NbBundle.getMessage(OutputPanel.class, "LBL_Browse_Output")); // NOI18N
    if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
        for (File file : chooser.getSelectedFiles()) {
            file = FileUtil.normalizeFile(file);
            listModel.addElement(file.getAbsolutePath());
            lastChosenFile = file;
        }
        applyChanges();
        updateButtons();
    }
}
 
Example 10
Source File: OpenFileAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Displays the specified file chooser and returns a list of selected files.
 *
 * @param  chooser  file chooser to display
 * @return  array of selected files,
 * @exception  org.openide.util.UserCancelException
 *                     if the user cancelled the operation
 */
public static File[] chooseFilesToOpen(JFileChooser chooser)
        throws UserCancelException {
    File[] files;
    do {
        int selectedOption = chooser.showOpenDialog(
            WindowManager.getDefault().getMainWindow());
        
        if (selectedOption != JFileChooser.APPROVE_OPTION) {
            throw new UserCancelException();
        }
        files = chooser.getSelectedFiles();
    } while (files.length == 0);
    return files;
}
 
Example 11
Source File: RObjectsPanel.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
private void _addActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event__addActionPerformed
  JFileChooser fc = new JFileChooser();
  fc.setMultiSelectionEnabled(true);
  fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
  fc.setFileFilter(new FileFilter() {

    @Override
    public boolean accept(File f) {
      return f.isDirectory() || f.getName().endsWith(".R") || f.getName().endsWith(".Rdata");
    }

    @Override
    public String getDescription() {
      return "R object file";
    }
  });
  if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION && fc.getSelectedFiles() != null) {
    File[] files = fc.getSelectedFiles();
    for (File file : files) {
      // System.out.println("+ " + file.getName());
      if (file.getName().endsWith(".R")) {
        if (R != null) {
          R.source(file);
        }
      } else if (file.getName().endsWith(".Rdata")) {
        if (R != null) {
          R.load(file);
        }
      } else {
        System.err.println("Not loading/sourcing " + file.getName());
      }
    }
  }
  update();
}
 
Example 12
Source File: FileChooserBuilder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Show an open dialog that allows multiple selection.
 * @return An array of files, or null if the user cancelled the dialog
 */
public File[] showMultiOpenDialog() {
    JFileChooser chooser = createFileChooser();
    chooser.setMultiSelectionEnabled(true);
    int result = chooser.showOpenDialog(findDialogParent());
    if (JFileChooser.APPROVE_OPTION == result) {
        File[] files = chooser.getSelectedFiles();
        return files == null ? new File[0] : files;
    } else {
        return null;
    }
}
 
Example 13
Source File: SpringCustomizerPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addFileButtonActionPerformed
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setMultiSelectionEnabled(true);
        chooser.setDialogTitle(NbBundle.getMessage(SpringCustomizerPanel.class, "LBL_ChooseFile")); //NOI18N
        chooser.setCurrentDirectory(basedir);
        int option = chooser.showOpenDialog(SwingUtilities.getWindowAncestor(groupFilesList));
        if (option == JFileChooser.APPROVE_OPTION) {
            boolean showDialog = false;
            List<File> newFiles = new LinkedList<File>();
            StringBuilder existing = new StringBuilder(
                    NbBundle.getMessage(SpringCustomizerPanel.class, "LBL_FileAlreadyAdded")).append("\n"); //NOI18N
            for (File file : chooser.getSelectedFiles()) {
                if (files.contains(file)) {
                    existing.append(file.getAbsolutePath()).append("\n"); //NOI18N
                    showDialog = true;
                } else {
                    newFiles.add(file);
                }
            }

            // remember last location
            basedir = chooser.getCurrentDirectory();
            addFiles(newFiles);
            if (showDialog) {
                DialogDisplayer.getDefault().notify(
                        new NotifyDescriptor.Message(existing.toString(), NotifyDescriptor.ERROR_MESSAGE));
            }
        }
}
 
Example 14
Source File: ZipDialog.java    From Compressor with GNU General Public License v2.0 5 votes vote down vote up
private void onArchiverFile(Archiver ma) {
	JFileChooser o = new JFileChooser(".");
	o.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
	o.setMultiSelectionEnabled(true);
	int returnVal = o.showOpenDialog(this);
	if (returnVal != JFileChooser.APPROVE_OPTION) {
		return;
	}
	File[] files = o.getSelectedFiles();

	JFileChooser s = new JFileChooser(".");
	FileNameExtensionFilter filter = ma.getFileFilter();
	s.addChoosableFileFilter(filter);
	returnVal = s.showSaveDialog(this);
	if (returnVal != JFileChooser.APPROVE_OPTION) {
		return;
	}
	File f = s.getSelectedFile();
	String filepath = f.getAbsolutePath();
	if (!filter.accept(f)) {// 确保一定有后缀
		filepath = filepath + "." + filter.getExtensions()[0];
	}

	try {
		ma.doArchiver(files, filepath);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 15
Source File: FileArrayEditor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Property change listaner attached to the JFileChooser chooser. */
public void propertyChange(PropertyChangeEvent e) {
    // Fix for IZ#36742 - FileArrayEditor fires each selection change twice
    if ( ANCESTOR.equals( e.getPropertyName()) ){
        myPropertyFired.set( null );
    }
    
    if (e.getSource() instanceof JFileChooser) {
        JFileChooser jfc = (JFileChooser) e.getSource();
        if (mode == jfc.DIRECTORIES_ONLY && jfc.DIRECTORY_CHANGED_PROPERTY.equals(e.getPropertyName())) {
            if (jfc.getSelectedFile() == null) {
                File dir = jfc.getCurrentDirectory();
                if (dir != null) {
                    setValue (new File[] {new File(dir.getAbsolutePath())});
                    return;
                }
            }
        }
    }
    
    if (( ! JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(e.getPropertyName())) && 
        ( ! JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(e.getPropertyName()))) {
            return;
    }
    if (! (e.getSource() instanceof JFileChooser)) {
        return;
    }
    JFileChooser chooser = (JFileChooser)e.getSource();
    File[] f = (File[])chooser.getSelectedFiles();
    if (f == null) {
        return;
    }
    
    // Fix for IZ#36742 - FileArrayEditor fires each selection change twice
    if ( isAlreadyHandled ( chooser , f , e.getPropertyName())){
        return;
    }
    
    if ((f.length == 0) && (chooser.getSelectedFile() != null)) {
        f = new File[] { chooser.getSelectedFile() };
    }
    
    for (int i = 0; i < f.length; i++) {
        if (!files && f[i].isFile ()) return;
        if (!directories && f[i].isDirectory ()) return;
    }

    if (baseDirectory != null) {
        for (int i = 0; i < f.length; i++) {
            String rel = FileEditor.getChildRelativePath(baseDirectory, f[i]);
            if (rel != null) {
                f[i] = new File(rel);
            }
        }
    }
    
    File[] nf = new File[f.length];
    for (int i = 0; i < f.length; i++) {
        // the next line is
        // workaround for JDK bug 4533419
        // it should be returned back to f[i] after the
        // mentioned bug is fixed in JDK.
        nf[i] = new File(f[i].getAbsolutePath());
    }
    setValue(nf);
    
    FileEditor.lastCurrentDir = chooser.getCurrentDirectory();
}
 
Example 16
Source File: MainPanel.java    From swift-explorer with Apache License 2.0 4 votes vote down vote up
protected void onCreateStoredObject() 
 {
 	List<StoredObject> sltObj = getSelectedStoredObjects() ;
 	if (sltObj != null && sltObj.size() > 1)
 		return ; // should never happen, because in such a case the menu is disable
 	StoredObject parentObject = (sltObj == null || sltObj.isEmpty()) ? (null) : (sltObj.get(0)) ;
 	
     Container container = getSelectedContainer();
     JFileChooser chooser = new JFileChooser();
     chooser.setMultiSelectionEnabled(true);
     chooser.setCurrentDirectory(lastFolder);
     
     final JPanel optionPanel = getOptionPanel ();
     chooser.setAccessory(optionPanel);
     AbstractButton overwriteCheck = setOverwriteOption (optionPanel) ;
     
     if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) 
     {
         File[] selectedFiles = chooser.getSelectedFiles();
         try 
         {
         	boolean overwriteAll = overwriteCheck.isSelected() ;
         	if (overwriteAll)
         	{
         		if (!confirm(getLocalizedString("confirm_overwrite_any_existing_files")))
         			return ;
         	}
	ops.uploadFiles(container, parentObject, selectedFiles, overwriteAll, getNewSwiftStopRequester (), callback);
	
	// We open the progress window, for it is likely that this operation
	// will take a while
	//if (selectedFiles != null /*&& selectedFiles.length > 1*/)
	//{
           //onProgressButton () ;
	//}
} 
         catch (IOException e) 
{
	logger.error("Error occurred while uploading a files.", e);
}
         lastFolder = chooser.getCurrentDirectory();
     }
 }
 
Example 17
Source File: ScreenStudio.java    From screenstudio with GNU General Public License v3.0 4 votes vote down vote up
private void mnuMainAddImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuMainAddImageActionPerformed
    JFileChooser chooser = new JFileChooser(mVideoOutputFolder);
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File f) {
            return f.isDirectory() || f.getName().toUpperCase().endsWith(".PNG") || f.getName().toUpperCase().endsWith(".JPG") || f.getName().toUpperCase().endsWith(".GIF") || f.getName().toUpperCase().endsWith(".BMP");
        }

        @Override
        public String getDescription() {
            return "Image Files";
        }
    });
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(true);
    chooser.showOpenDialog(this);
    if (chooser.getSelectedFile() != null) {
        //add new source...
        screenstudio.targets.Source source = new screenstudio.targets.Source(cboSourceViews.getItemCount());
        source.setCurrentViewIndex(cboSourceViews.getSelectedIndex());
        source.Views.get(source.CurrentViewIndex).remoteDisplay = true;
        source.setType(SourceType.Image);

        if (chooser.getSelectedFiles().length <= 1) {
            File image = chooser.getSelectedFile();
            source.setSourceObject(image);
        } else {
            try {
                SlideShow images = new SlideShow(chooser.getSelectedFiles());
                source.setSourceObject(images);
            } catch (IOException ex) {
                Logger.getLogger(ScreenStudio.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        source.Views.get(source.CurrentViewIndex).X = 0;
        source.Views.get(source.CurrentViewIndex).Y = 0;
        source.Views.get(source.CurrentViewIndex).Width = 200;
        source.Views.get(source.CurrentViewIndex).Height = 200;
        source.Views.get(source.CurrentViewIndex).Alpha = 1f;
        source.Views.get(source.CurrentViewIndex).Order = mSources.size();
        source.setStartTime(0L);
        source.setEndTime(0L);
        source.setTransitionStart(Transition.NAMES.None);
        source.setTransitionStop(Transition.NAMES.None);
        source.setEffect(Effect.eEffects.None);
        source.initOtherViews();
        bindingGroup.getBinding("MySource").unbind();
        mSources.add(source);
        bindingGroup.getBinding("MySource").bind();
        updateColumnsLayout();
        updateRemoteSources();
    }
}
 
Example 18
Source File: MultiRepAnalysis.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new MultiRepAnalysis
 * @param arguments optional arguments to define the files and folders to analyze<br>
 * 		the <b>first</b>  element can be an optional replay source to load<br>
 * 		the <b>second</b> element can be an optional replay list to load<br>
 * 		the <b>third</b>  element can be a File array to perform the Multi-rep analysis on
 */
public MultiRepAnalysis( final Object... arguments ) {
	super( arguments.length == 0 ? Language.getText( "module.multiRepAnal.opening" ) : null ); // This title does not have a role as this internal frame is not displayed until replays are chosen, and then title is changed anyway
	
	setFrameIcon( Icons.CHART_UP_COLOR );
	
	if ( arguments.length == 0 ) {
		final JFileChooser fileChooser = new JFileChooser( GeneralUtils.getDefaultReplayFolder() );
		fileChooser.setDialogTitle( Language.getText( "module.multiRepAnal.openTitle" ) );
		fileChooser.setFileFilter( GuiUtils.SC2_REPLAY_FILTER );
		fileChooser.setAccessory( GuiUtils.createReplayFilePreviewAccessory( fileChooser ) );
		fileChooser.setFileView( GuiUtils.SC2GEARS_FILE_VIEW );
		fileChooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
		fileChooser.setMultiSelectionEnabled( true );
		if ( fileChooser.showOpenDialog( MainFrame.INSTANCE ) == JFileChooser.APPROVE_OPTION )
			this.files = fileChooser.getSelectedFiles();
		else {
			dispose();
			this.files = null;
			return;
		}
	}
	else {
		if ( arguments.length > 0 && arguments[ 0 ] != null ) {
			// Replay source
			this.files = loadReplaySourceFile( (File) arguments[ 0 ] );
		}
		else if ( arguments.length > 1 && arguments[ 1 ] != null ) {
			// Replay list
			// TODO this can be sped up by reading the replay list by hand and only use the file name!
			final List< Object[] > dataList = ReplaySearch.loadReplayListFile( (File) arguments[ 1 ] );
			this.files = new File[ dataList.size() ];
			for ( int i = dataList.size() - 1; i >= 0; i-- )
				this.files[ i ] = new File( (String) dataList.get( i )[ ReplaySearch.COLUMN_FILE_NAME ] );
		}
		else if ( arguments.length > 2 && arguments[ 2 ] != null ) {
			// Replays to open
			this.files = (File[]) arguments[ 2 ];
		}
		else
			throw new RuntimeException( "The source for Multi-rep analysis is incorrectly specified!" );
	}
	
	setTitle( Language.getText( "module.multiRepAnal.title", counter.incrementAndGet() ) );
	
	buildGUI();
}
 
Example 19
Source File: GuiUtilities.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public static File[] showOpenFilesDialog( final Component parent, final String title, final boolean multiselection,
        final File initialPath, final FileFilter filter ) {
    RunnableWithParameters runnable = new RunnableWithParameters(){
        public void run() {
            JFileChooser fc = new JFileChooser();
            fc.setDialogTitle(title);
            fc.setDialogType(JFileChooser.OPEN_DIALOG);
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fc.setMultiSelectionEnabled(multiselection);
            fc.setCurrentDirectory(initialPath);
            if (filter != null)
                fc.setFileFilter(filter);
            fc.setFileHidingEnabled(false);
            int r = fc.showOpenDialog(parent);
            if (r != JFileChooser.APPROVE_OPTION) {
                this.returnValue = null;
                return;
            }

            if (fc.isMultiSelectionEnabled()) {
                File[] selectedFiles = fc.getSelectedFiles();
                this.returnValue = selectedFiles;
            } else {
                File selectedFile = fc.getSelectedFile();
                if (selectedFile != null && selectedFile.exists())
                    PreferencesHandler.setLastPath(selectedFile.getAbsolutePath());
                this.returnValue = new File[]{selectedFile};
            }

        }
    };
    if (SwingUtilities.isEventDispatchThread()) {
        runnable.run();
    } else {
        try {
            SwingUtilities.invokeAndWait(runnable);
        } catch (Exception e) {
            Logger.INSTANCE.insertError("", "Can't show chooser dialog '" + title + "'.", e);
        }
    }
    return (File[]) runnable.getReturnValue();
}
 
Example 20
Source File: OpenStegoUI.java    From openstego with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Method to get the display file chooser and return the selected file name
 *
 * @param dialogTitle Title for the file chooser dialog box
 * @param filterDesc Description to be displayed for the filter in file chooser
 * @param allowedExts Allowed file extensions for the filter
 * @param allowFileDir Type of objects allowed to be selected (FileBrowser.ALLOW_FILE,
 *        FileBrowser.ALLOW_DIRECTORY or FileBrowser.ALLOW_FILE_AND_DIR)
 * @param multiSelect Flag to indicate whether multiple file selection is allowed or not
 * @return Name of the selected file (null if no file was selected)
 */
public String getFileName(String dialogTitle, String filterDesc, List<String> allowedExts, int allowFileDir, boolean multiSelect) {
    int retVal = 0;
    String fileName = null;
    File[] files = null;

    JFileChooser chooser = new JFileChooser(lastFolder);
    chooser.setMultiSelectionEnabled(multiSelect);
    switch (allowFileDir) {
        case ALLOW_FILE:
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            break;
        case ALLOW_DIRECTORY:
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            break;
        case ALLOW_FILE_AND_DIR:
            chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            break;
    }

    if (filterDesc != null) {
        chooser.setFileFilter(new FileBrowserFilter(filterDesc, allowedExts));
    }
    chooser.setDialogTitle(dialogTitle);
    retVal = chooser.showOpenDialog(null);

    if (retVal == JFileChooser.APPROVE_OPTION) {
        if (multiSelect) {
            StringBuffer fileList = new StringBuffer();
            files = chooser.getSelectedFiles();
            for (int i = 0; i < files.length; i++) {
                if (i != 0) {
                    fileList.append(";");
                }
                fileList.append(files[i].getPath());
            }
            fileName = fileList.toString();
        } else {
            fileName = chooser.getSelectedFile().getPath();
        }
        lastFolder = chooser.getSelectedFile().getParent();
    }

    return fileName;
}