Creating a JFileChooser Dialog - Java Swing

Java examples for Swing:JFileChooser

Description

Creating a JFileChooser Dialog

Demo Code


import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    //from w  ww. ja  v a 2 s  .c o  m
    String filename = File.separator + "tmp";
    JFileChooser fc = new JFileChooser(new File(filename));

    fc.showOpenDialog(frame);
    File selFile = fc.getSelectedFile();

    fc.showSaveDialog(frame);
    selFile = fc.getSelectedFile();

    // Create the actions
    Action openAction = new OpenFileAction(frame, fc);
    Action saveAction = new SaveFileAction(frame, fc);

    // Create buttons for the actions
    JButton openButton = new JButton(openAction);
    JButton saveButton = new JButton(saveAction);

    // Add the buttons to the frame and show the frame
    frame.getContentPane().add(openButton, BorderLayout.NORTH);
    frame.getContentPane().add(saveButton, BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
  }
}
//This action creates and shows a modal open-file dialog.
class OpenFileAction extends AbstractAction {
 JFrame frame;
 JFileChooser chooser;

 OpenFileAction(JFrame frame, JFileChooser chooser) {
     super("Open...");
     this.chooser = chooser;
     this.frame = frame;
 }

 public void actionPerformed(ActionEvent evt) {
     // Show dialog; this method does not return until dialog is closed
     chooser.showOpenDialog(frame);

     // Get the selected file
     File file = chooser.getSelectedFile();
 }
}

//This action creates and shows a modal save-file dialog.
class SaveFileAction extends AbstractAction {
 JFileChooser chooser;
 JFrame frame;

 SaveFileAction(JFrame frame, JFileChooser chooser) {
     super("Save As...");
     this.chooser = chooser;
     this.frame = frame;
 }

 public void actionPerformed(ActionEvent evt) {
     // Show dialog; this method does not return until dialog is closed
     chooser.showSaveDialog(frame);

     // Get the selected file
     File file = chooser.getSelectedFile();
 }
}

Related Tutorials