Leon Anavi
IT Tips && Tricks

Java

Created: 18.07.2009 16:51 Last Modified: 19.07.2009 02:49 Views: 9164
Keywords: File, JFileChooser, Swing

Choose a File

Managing files is the most common operation. Instance of class JFileChooser should be used to provide ability of choosing files in a java 2 desktop swing application. First create an instance of JFileChooser. At appropriate location call the method showOpenDialog and beware of exceptions. The return value stands for the user actions. If the user has selected a file it will be equal to JFileChooser.APPROVE_OPTION otherwise to JFileChooser.CANCEL_OPTION.

Example:

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.io.File;
// * * *
private JFileChooser m_FileChooser;
// * * *
m_FileChooser = new JFileChooser();
//To select only directories use JFileChooser.DIRECTORIES_ONLY 
//or JFileChooser.FILES_ONLY for files
m_FileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
//Additional restrictions can be set by adding a filter
// * * *
    try
    {
        int nState = m_FileChooser.showOpenDialog(null);
        if (nState  == JFileChooser.APPROVE_OPTION) 
        //if (nState != JFileChooser.CANCEL_OPTION)
        {
            //we have the selected file
            File SelectedFile = m_FileChooser.getSelectedFile();
            String sFilename = SelectedFile.getPath() + SelectedFile.getName();
            JOptionPane.showMessageDialog(null, sFilename);
        } 
        else
        {
            JOptionPane.showMessageDialog(null, "User did not choose a file.");
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    } 

Further reading:

How to Use File Choosers

Class reference:

Class JFileChooser
Class File


  Home | About | Contact | Disclaimer | Sitemap © 2009-2022 Leon Anavi. All rights reserved.