JFileChooser
JFileChooser Swing Example
The JFileChooser Component is used to create a cross platform directory explorer that can be used for a Java Desktop Application. For this blog post, I’ll showcase the how to use the component and call it from a Java class.
1. Import the necessary objects
We need to import the following objects on your java class.
import java.io.File; import javax.swing.JFileChooser; import javax.swing.JFrame;
2. Create a new JFileChooser Object
Create the new JFileChooser Object and set the default directory
... JFileChooser jFileChooser = new JFileChooser(); jFileChooser.setCurrentDirectory(new File("/User/alvinreyes")); ...
3. Show the file explorer dialog
Call the showOpenDialog
method to show the jfilechooser. It needs a component on where to run to, so we need to add the JFrame object here.
... int result = jFileChooser.showOpenDialog(new JFrame()); ...
4. Add code to check the selected file
We need to add this code so that we can pick up the selected file by the user
... if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = jFileChooser.getSelectedFile(); System.out.println("Selected file: " + selectedFile.getAbsolutePath()); } ...
5. Launch the Java class
You will see the following screen as shown:
5. Code snippet
SampleJFileChooser.java
package com.jgc.areyes.main; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JFrame; public class SampleJFileChooser { public SampleJFileChooser(){ JFileChooser jFileChooser = new JFileChooser(); jFileChooser.setCurrentDirectory(new File("/User/alvinreyes")); int result = jFileChooser.showOpenDialog(new JFrame()); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = jFileChooser.getSelectedFile(); System.out.println("Selected file: " + selectedFile.getAbsolutePath()); } } public static void main(String[] args) { new SampleJFileChooser(); } }
6. Download the Eclipse project of this tutorial:
This was an example of JFileChooser
.
Download
You can download the full source code of this example here : jfilechooser-sample.zip
You can download the full source code of this example here : jfilechooser-sample.zip