Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Spring Framework | Web Services | BioInformatics | Java Server Faces | Jboss 3.0 tutorial | Hibernate 3.0 | XML
 
 
Hot Web Programming Job

 

Tutorial Categories: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML


 

Java Tutorials

Core Java
JSP
Servlet
JDBC
Hibernate
Struts 1
Struts 2
JSF
Spring
J2EE
J2ME
Web Services
Ajax
Dojo
MySQL
Latest Comments
Contents are not d
Please Use JAVA no
hidden tag in orku
Getting good knowl
Why the output on
  All Comments...
 

 

 
Struts Tutorials
*Stuts TOC
*Apache Struts Introduction
* Struts Controller
* Struts Action Class
* Struts ActionFrom Class
* Using Struts HTML Tags
*Struts Validator Framework    
*Client Side Address Validation    
*Struts Tiles
*tiles-defs.xml
*Struts DynaActionForm
*Struts File Upload
*Struts DataSource
*AGGREGATING ACTIONS
*Internationalization
Struts Resources
*Struts Books
*Struts Articles
*Struts Frameworks
*Struts IDE
*Struts Alternative
*Struts Links
*Struts Presentations
*Struts Projects
*Struts Software
*Struts Reference
*Struts Resources
*Other Struts Tutorial
Visit Forum! Post Questions!
Jobs At RoseIndia.net!

Have tutorials?
Add your tutorial to our Java Resource and get tons of hits.

We offer free hosting for your tutorials. and exposure for thousands of readers. drop a mail
roseindia_net@yahoo.com
 
   

 
Join For Newsletter

Powered by groups.yahoo.com
Visit Group! Post Questions!

Java: JFileChooser

The javax.swing.JFileChooser class is used to create file choosers for selecting files or directories to open or save.

To Create an Open File Chooser

The sample code below uses JFileChooser in the Open button action listener.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
 69 
 70 
 71 
 72 
 73 
 74 
 75 
 76 
 77 
 78 
 79 
 80 
 81 
 82 
 83 
 84 
 85 
 86 
 87 
 88 
 89 
// File   : filechooser/CountWords.java
// Purpose: Counts words in file.
//          Illustrates menus, JFileChooser, Scanner..
// Author : Fred Swartz
// Date   : 2005-02-23, 2005-12-02

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;

//////////////////////////////////////////////////////// CountWords
public class CountWords extends JFrame {

    //... Instance variables
    JTextField   m_fileNameTF  = new JTextField(15);
    JTextField   m_wordCountTF = new JTextField(4);
    JFileChooser m_fileChooser = new JFileChooser();

    //================================================== constructor
    CountWords() {
        m_fileNameTF.setEditable(false);
        m_wordCountTF.setEditable(false);
        JButton openButton = new JButton("Open");

        //... Add listeners
        openButton.addActionListener(new OpenAction());

        //... Create contant pane, layout components
        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());
        content.add(openButton);
        content.add(m_fileNameTF);
        content.add(new JLabel("Word Count"));
        content.add(m_wordCountTF);

        //... Set window characteristics
        this.setTitle("Count Words");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setContentPane(content);
        this.pack();
    }

    //============================================= countWordsInFile
    private int countWordsInFile(File f) {

        int numberOfWords = 0;  // For counting words.

        try {
            Scanner wordScanner = new Scanner(f);
            wordScanner.useDelimiter("[^A-Za-z]+");

            while (wordScanner.hasNext()) {
                String word = wordScanner.next();
                numberOfWords++;
            }
            wordScanner.close();     // Close Scanner's file.

        } catch (FileNotFoundException fnfex) {
            JOptionPane.showMessageDialog(CountWords.this,
                        "You gave me an unreadable file");
        }
        return numberOfWords;
    }


    ///////////////////////////////////////////////////// OpenAction
    class OpenAction implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            //... Open a file dialog.
            int retval = m_fileChooser.showOpenDialog(CountWords.this);
            if (retval == JFileChooser.APPROVE_OPTION) {
                //... The user selected a file, process it.
                File file = m_fileChooser.getSelectedFile();

                //... Update user interface.
                m_fileNameTF.setText(file.getName());
                m_wordCountTF.setText("" + countWordsInFile(file));
            }
        }
    }

    //========================================================= main
    public static void main(String[] args) {
        JFrame window = new CountWords();
        window.setVisible(true);
    }
}

To display a file chooser

Use one of three methods to display the dialog after it has been created.

 
   r = fc.showOpenDialog(owner); // button labeled "Open"
   r = fc.showSaveDialog(owner); // button labeled "Save"
   r = fc.showDialog(owner, title); 

The owner parameter is the component (eg, JFrame, JPanel, ...) over which the dialog should be centered. You can use null for the owner, which will put the dialog in the center of the screen. To get the enclosing class's instance, as in this example, write the enclosing class name followed by ".this". The title parameter is a string that is used as the dialog's title and accept button text.

Checking the return value

The user may either select a file or directory, or click CANCEL or close the file chooser window. If the user selected a file or directory, the value returned will be JFileChooser.APPROVE_OPTION. Always check this value. For example,

int retval = fc.showOpenDialog(null);
if (retval == JFileChooser.APPROVE_OPTION) {
    . . . // The user did select a file.;

Getting the selected file or directory

After checking for JFileChooser.APPROVE_OPTION, the File value of the selection is returned from a call on getSelectedFile.

int retval = fc.showOpenDialog(null);
if (retval == JFileChooser.APPROVE_OPTION) {
    File myFile = fc.getSelectedFile();
    // DO YOUR PROCESSING HERE. OPEN FILE OR ...
}

Why a file chooser is often an instance variable

Altho a new file chooser can be created inside a listener, there are advantages to creating it once outside and reusing it.

  • A file chooser remembers the directory that was last used so any reuse opens in the same directory.
  • It is also more efficient since it is created only once and customizations only have to be done once. This increases the response speed.

Files, directories, or both

By default a file chooser allows the user to select only files. To allow selection of either files or directories, or only directories, use one of the following calls.

   fc.setFileSelectionMode(JFileChooser.FILES_ONLY);   // default
   fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
   fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

Filtering files

You can specify the kinds of files that should be shown (eg, with a specific extension, ...), but supplying a JFileFilter.

 
   myChooser.setFileFilter(FileFilter filter);

See FileFilter. [NEEDS MORE WORK]

Specify a start directory in the constructor

The file chooser will start the file dialog at some default directory, for example, "C:\My Documents". To start the dialog at a different directory (called the current directory), specify the directory path as a String or File value in the JFileChooser constructor.

JFileChooser m_fileChooser = new JFileChooser("C:\home");

The current directory is ".".

Portability warning: If you put system specific file paths in your code, the program will not be portable to other systems. Note that the above call is therefore not portable.

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.