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:

Figure 1. Launch Java
Figure 1. Launch Java

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

Alvin Reyes

Alvin has an Information Technology Degree from Mapua Institute of Technology. During his studies, he was already heavily involved in a number of small to large projects where he primarily contributes by doing programming, analysis design. After graduating, he continued to do side projects on Mobile, Desktop and Web Applications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button