Academic Java    Java Tutorial  >  Swing  >  JFileChooser

JFileChooser Example

Java JFileChooser EXAMPLE output This JFileChooser example allows the user to open and read a text file, edit it, and then save the file.

The class extends a JFrame and implements an ActionListener interface. A menu is placed in the frame and a selection from it is caught by the actionPerformed() method of the listener interface. A method to construct the JFileChooser is then called.

In this JFileChooser example the user has edited some text and is about to save it to file.
// JFileChooser Example
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

class JFileChooserExample extends JFrame implements ActionListener {
   private JEditorPane jep = new JEditorPane();
   public JFileChooserExample() {
      super("Editor");
      Container cp = getContentPane( );
      cp.add(new JScrollPane(jep), BorderLayout.CENTER);
      JMenu menu = new JMenu("File");
      menu.add(make("Open")); menu.add(make("Save"));
      menu.add(make("Quit"));
      JMenuBar menuBar = new JMenuBar();
      menuBar.add(menu); setJMenuBar(menuBar);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(200,300);
   }

   public void actionPerformed(ActionEvent e) {
      String ac = e.getActionCommand();
      if(ac.equals("Open")) openFile();
      else if(ac.equals("Save")) saveFile();
      else if(ac.equals("Quit")) System.exit(0);
   }

   private void openFile() {
      JFileChooser jfc = new JFileChooser();
      int result = jfc.showOpenDialog(this);
      if(result == JFileChooser.CANCEL_OPTION) return;
      try {
         File file = jfc.getSelectedFile();
         BufferedReader br = new BufferedReader(new FileReader(file));
         String s=""; int c=0;
         while((c=br.read())!=-1) s+=(char)c;
         br.close(); jep.setText(s);
      } catch (Exception e) {
         JOptionPane.showMessageDialog(this,e.getMessage(),
         "File error",JOptionPane.ERROR_MESSAGE);}
   }

   private void saveFile( ) {
      JFileChooser jfc = new JFileChooser();
      int result = jfc.showSaveDialog(this);
      if(result == JFileChooser.CANCEL_OPTION) return;
      File file = jfc.getSelectedFile();
      try {
         BufferedWriter bw = new BufferedWriter(new FileWriter(file));
         bw.write(jep.getText());
         bw.close();
      }
      catch (Exception e) {
         JOptionPane.showMessageDialog(
            this,
            e.getMessage(),
            "File Error",
            JOptionPane.ERROR_MESSAGE
         );
      }
   }

   private JMenuItem make(String name) {
      JMenuItem m = new JMenuItem(name);
      m.addActionListener(this);
      return m;
   }

   public static void main(String[] args) {
      new JFileChooserExample().setVisible(true);}
}