Java Swing Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.01

javax.swing.JFileChooser - File Chooser Dialog Box

This section provides a tutorial example on how to use the javax.swing.JFileChooser class to create a file chooser dialog box for the Open command and the Save command.

If you want users to enter a file name to read or write data, you may want to use the javax.swing.JFileChooser class, the file chooser dialog box. It has some interesting methods:

  • setCurrentDirectory(File) - Method to set the current directory for the file chooser.
  • setSelectedFile(File) - Method to set the default selected file.
  • setFileFilter(FileFilter) - Method to define a file type based on file extensions as a file selection filter.
  • setFileSelectionMode(int) - Method to set the selection mode out 3 options: FILES_ONLY, DIRECTORIES_ONLY and FILES_AND_DIRECTORIES.
  • getSelectedFile() - Method to return the selected file as a File object.
  • showOpenDialog(Component) - Method to display this file chooser dialog box, wait for user input and return integer code: CANCEL_OPTION, APPROVE_OPTION, or ERROR_OPTION.

Here is an example program I wrote to test the JFileChooser class:

/**
 * JEditorPaneFileChooser.java
 * Copyright (c) 2009 by Dr. Herong Yang, http://www.herongyang.com/
 */
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
public class JEditorPaneFileChooser implements ActionListener {
   JFrame myFrame = null;
   JEditorPane myPane = null;
   JMenuItem cmdOpen = null;
   JMenuItem cmdSave = null;
   String dirName = "\\herong\\swing\\";
   String fileName = "JEditorPane.txt";

   public static void main(String[] a) {
      (new JEditorPaneFileChooser()).test();
   }
   private void test() {
      myFrame = new JFrame("JEditorPane JFileChooser Test");
      myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      myFrame.setSize(300,200);
      
      myPane = new JEditorPane();
      myPane.setContentType("text/plain");
      myPane.setText(
         "Hello computer! - \u7535\u8111\u4F60\u597D\uFF01\n"
         + "Welcome to Herong's Website!\n"
         + "\u6B22\u8FCE\u4F60\u8BBF\u95EE\u548C\u8363\u7F51\u7AD9"
         + "\uFF01\nwww.herongyang.com");
      myFrame.setContentPane(myPane);

      JMenuBar myBar = new JMenuBar();
      JMenu myMenu = getFileMenu();
      myBar.add(myMenu); 
      myFrame.setJMenuBar(myBar);

      myFrame.setVisible(true);
   }
   private JMenu getFileMenu() {
      JMenu myMenu = new JMenu("File");
      cmdOpen = new JMenuItem("Open");
      cmdOpen.addActionListener(this);
      myMenu.add(cmdOpen);

      cmdSave = new JMenuItem("Save");
      cmdSave.addActionListener(this);
      myMenu.add(cmdSave);
      return myMenu;
   }
   public void actionPerformed(ActionEvent e) {
      JFileChooser chooser = new JFileChooser();
      chooser.setCurrentDirectory(new File(dirName));
      chooser.setSelectedFile(new File(fileName));
      chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

      FileNameExtensionFilter filter = new FileNameExtensionFilter(
        ".txt and .java files", "txt", "java");
      chooser.setFileFilter(filter);

      Object cmd = e.getSource();
      try {
         if (cmd == cmdOpen) {
            int code = chooser.showOpenDialog(myPane);
            if (code == JFileChooser.APPROVE_OPTION) {
               File selectedFile = chooser.getSelectedFile();
               fileName = selectedFile.getName();
               FileInputStream fis = 
                  new FileInputStream(selectedFile);
               InputStreamReader in = 
                  new InputStreamReader(fis, Charset.forName("UTF-8")); 
               char[] buffer = new char[1024];
               int n = in.read(buffer);
               String text = new String(buffer, 0, n);
               myPane.setText(text);
               in.close();
            }
         } else if (cmd == cmdSave) {
            int code = chooser.showOpenDialog(myPane);
            if (code == JFileChooser.APPROVE_OPTION) {
               File selectedFile = chooser.getSelectedFile();
               fileName = selectedFile.getName();
               FileOutputStream fos = 
                  new FileOutputStream(selectedFile);
               OutputStreamWriter out = 
                  new OutputStreamWriter(fos, Charset.forName("UTF-8")); 
               out.write(myPane.getText());
               out.close();
            }
         }
      } catch (Exception f) {
      	 f.printStackTrace();
      }
   }
}

If you run this example, you will see a text editor pane displayed with the initial text content including some Chinese characters.

If you click the Open command in the File menu, a file chooser dialog box will be displayed. You can click the Details icon to change the list of files with detailed information. You can click the Date Modified column header to sort the list of files as shown in the picture below:
Editor Pane Test

Interesting notes about this tutorial example:

  • "chooser.setCurrentDirectory(new File(dirName));" statement is used to set the default directory to \herong\swing\.
  • "chooser.setSelectedFile(new File(fileName));" statement is used to set the default file to JEditorPane.txt.
  • "chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);" statement is used to set the selection mode to file only.
  • "chooser.setFileFilter(filter);" statement is used to set the file filter for .txt and .java files only.
  • Note that the constructor, FileNameExtensionFilter(description, ext1, ext2, ...), has a parameter list of variable length.

Sample programs listed in this section have been tested with JDK 1.6.0.

Last update: 2009.

Table of Contents

 About This Java Swing Tutorial Book

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

JEditorPane - The Editor Pane Class

 Creating a Simple Plain Text Editor Pane

 Saving Text from an Editor Pane

 Editing HTML in an Editor Pane

 Editing Unicode Characters in an Editor Pane

javax.swing.JFileChooser - File Chooser Dialog Box

 References

 Printable Copy - PDF Version

Dr. Herong Yang, updated in 2009
javax.swing.JFileChooser - File Chooser Dialog Box