This article walks through developing a custom file picker component in Java Swing. In swing applications, there would be a need to have a GUI component that allows users to specify a file to be opened or saved. There is no such built-in component in Swing, so we’re going to create a new one by extending JFileChooserclass and some standard swing components. The component’s UI looks like this:

 

file picker component

 

This file picker contains a label, followed by a text field and a button. When the button is clicked, an open or save dialog appears which let the user to pick up a file. Once selected, the file’s absolute path is shown in the text field.

Let’s see how the component is coded.

 

1. Source code of JFilePicker component

There are two source file that forms the file picker component:

Source code of JFilePicker class:

package net.codejava.swing;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class JFilePicker extends JPanel {
	private String textFieldLabel;
	private String buttonLabel;
	
	private JLabel label;
	private JTextField textField;
	private JButton button;
	
	private JFileChooser fileChooser;
	
	private int mode;
	public static final int MODE_OPEN = 1;
	public static final int MODE_SAVE = 2;
	
	public JFilePicker(String textFieldLabel, String buttonLabel) {
		this.textFieldLabel = textFieldLabel;
		this.buttonLabel = buttonLabel;
		
		fileChooser = new JFileChooser();
		
		setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		// creates the GUI
		label = new JLabel(textFieldLabel);
		
		textField = new JTextField(30);
		button = new JButton(buttonLabel);
		
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent evt) {
				buttonActionPerformed(evt);				
			}
		});
		
		add(label);
		add(textField);
		add(button);
		
	}
	
	private void buttonActionPerformed(ActionEvent evt) {
		if (mode == MODE_OPEN) {
			if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
				textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
			}
		} else if (mode == MODE_SAVE) {
			if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
				textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
			}
		}
	}

	public void addFileTypeFilter(String extension, String description) {
		FileTypeFilter filter = new FileTypeFilter(extension, description);
		fileChooser.addChoosableFileFilter(filter);
	}
	
	public void setMode(int mode) {
		this.mode = mode;
	}
	
	public String getSelectedFilePath() {
		return textField.getText();
	}
	
	public JFileChooser getFileChooser() {
		return this.fileChooser;
	}
}
Source code of FileTypeFilter class:

package net.codejava.swing;

import java.io.File;
import javax.swing.filechooser.FileFilter;

public class FileTypeFilter extends FileFilter {

	private String extension;
	private String description;
	
	public FileTypeFilter(String extension, String description) {
		this.extension = extension;
		this.description = description;
	}
	
	@Override
	public boolean accept(File file) {
		if (file.isDirectory()) {
			return true;
		}
		return file.getName().toLowerCase().endsWith(extension);
	}
	
	public String getDescription() {
		return description + String.format(" (*%s)", extension);
	}
}


 

 

2. How to use JFilePicker class

The constructor of JFilePicker class accepts two parameters:

    • textFieldLabel: label for the text field.
    • buttonLabel: label for the button.
So to create an object of this component:

JFilePicker filePicker = new JFilePicker("Pick a file", "Browse...");

Next, we specify mode of the dialog, open or save:

filePicker.setMode(JFilePicker.MODE_OPEN);

or:

filePicker.setMode(JfilePicker.MODE_SAVE);
File extension filters can be added likes this:

filePicker.addFileTypeFilter(".jpg", "JPEG Images");
filePicker.addFileTypeFilter(".mp4", "MPEG-4 Videos");
And the selected file’s path can be retrieved using getSelectedFilePath()method:

String filePath = filePicker.getSelectedFilePath();
The JFilePicker class also provides a mean to access the JFileChooser class directly, in case you want to do more tweaks:

JFileChooser fileChooser = filePicker.getFileChooser();
fileChooser.setCurrentDirectory(new File("D:/")); 
 

3. JFilePicker component example program

And following is an example program that uses the JFilePicker component we created above. It is a very simple JFrame which contains only the file picker component. Here is the source code:

package net.codejava.swing;

import java.awt.FlowLayout;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class TestJFilePicker extends JFrame {

	public TestJFilePicker() {
		super("Test using JFilePicker");
		
		setLayout(new FlowLayout());

		// set up a file picker component
		JFilePicker filePicker = new JFilePicker("Pick a file", "Browse...");
		filePicker.setMode(JFilePicker.MODE_SAVE);
		filePicker.addFileTypeFilter(".jpg", "JPEG Images");
		filePicker.addFileTypeFilter(".mp4", "MPEG-4 Videos");
		
		// access JFileChooser class directly
		JFileChooser fileChooser = filePicker.getFileChooser();
		fileChooser.setCurrentDirectory(new File("D:/"));
		
		// add the component to the frame
		add(filePicker);
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(520, 100);
		setLocationRelativeTo(null);	// center on screen
	}
	
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				new TestJFilePicker().setVisible(true);
			}
		});
	}

}
When running, the program looks like the following screenshot:

JFilePicker test program

When clicking on the Browse button:

save dialog

And path of the selected file is shown in the text field:

path of selected file

 

Related Swing File Chooser Tutorials:

 

Other Java Swing Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (FileTypeFilter.java)FileTypeFilter.java[File extension filter class]0.6 kB
Download this file (JFilePicker.java)JFilePicker.java[file picker component class]2 kB
Download this file (TestJFilePicker.java)TestJFilePicker.java[file picker test program]1 kB

Add comment

   


Comments 

#5rashmi2019-11-21 01:55
thanks for sharing in advance. thank you.
thanks for sharing in advance. thank you.
Quote
#4Ayan Chakraborty2018-07-26 01:53
helpful for my project...i am a beginner in java especially in netbeans,so i cant create a file picker .thanks for providing these.
Quote
#3saumya gupta2016-04-12 03:35
Can you tell me how to save the selected file in another location?
Quote
#2Nama2014-08-06 17:00
Hi Linify,
You can disable all files filter easily, just calling:

setAcceptAllFileFilterUsed(false)
Quote
#1Linify2014-08-06 05:33
I tried your TestJFilePicker.java but it does not only limits .jpg and .mp4 file. It allows ALL files to be selected. How do I make it so only the .jpg and .mp4 files can be selected???
Quote