JFileChooser
Create file chooser dialog
In this tutorial we are going to learn how to create a File Chooser Dialog in a Java Desktop Application. We all use file chooser dialogs on a daily basis. It is a very important component when you want to upload a file or to process a file in a GUI Application, because it lets the user choose the file he wants very easily.
Basically, to create a file chooser dialog, one should follow these steps:
- Create a new
JFrame
. - Use
getContentPane().setLayout(new FlowLayout())
to set flow layout for the frame. - Create a new
JButton
that will fire up the file chooser. - Add a new
ActionListener
to the button. Override theactionPerformed
method. Now every time the user pressed the button, this method will fire up. Inside this method we are going to create the pop up dialog. - To create that dialog, create a new
JFileChooser
to a file path. - Use
showOpenDialog
to pop up an “Open File” file chooser dialog. - Use
showSaveDialog
to pop up a “Save File” file chooser dialog.
Let’s see the code snippet that follows:
package com.javacodegeeks.snippets.desktop; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; public class CreateColorChooserDialog { private static final long serialVersionUID = 1L; private static void createAndShowGUI() { // Create and set up the window. final JFrame frame = new JFrame("Centered"); // Display the window. frame.setSize(200, 200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set flow layout for the frame frame.getContentPane().setLayout(new FlowLayout()); JButton button = new JButton("Choose file/directory"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { createFileChooser(frame); } }); frame.getContentPane().add(button); } private static void createFileChooser(final JFrame frame) { String filename = File.separator+"tmp"; JFileChooser fileChooser = new JFileChooser(new File(filename)); // pop up an "Open File" file chooser dialog fileChooser.showOpenDialog(frame); System.out.println("File to open: " + fileChooser.getSelectedFile()); // pop up an "Save File" file chooser dialog fileChooser.showSaveDialog(frame); System.out.println("File to save: " + fileChooser.getSelectedFile()); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
This was an example on how to create a file chooser dialog in a Java Desktop Application.