Pages

Create file chooser using JFileChooser

Source code below will show you, how to create a file chooser in java using JFileChooser class.

************************************************************************
COMPLETE SOURCE CODE FOR : CreateFileChooserUsingJFileChooser.java
************************************************************************


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

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

import java.awt.FlowLayout;

public class CreateFileChooserUsingJFileChooser implements ActionListener
{
//Create file chooser using JFileChooser
JFileChooser fileChooser=new JFileChooser();

//Create a button that use to open file chooser
JButton button=new JButton("Click here to open file chooser");

//Create a JFrame that use to place created button
//JFrame title is ( Create file chooser using JFileChooser )
JFrame frame=new JFrame("Create file chooser using JFileChooser");

public CreateFileChooserUsingJFileChooser()
{
//add ActionListener to created button
button.addActionListener(this);

//set JFrame layout to FlowLayout
frame.setLayout(new FlowLayout());

//add button into JFrame
frame.add(button);

//set default close operation for JFrame
//So when you click window close button, this program will exit
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//set JFrame size to :
//WIDTH : 500 pixels
//HEIGHT : 500 pixels
frame.setSize(500,500);

//Make your JFrame visible. So we can see it
frame.setVisible(true);
}

//Action that will take by button
public void actionPerformed(ActionEvent event)
{
//When you click the button, a file chooser will appear
if(event.getSource()==button)
{
//Show file chooser with title ( Choose a file )
fileChooser.showDialog(frame,"Choose a file");
}
}

public static void main(String[]args)
{
CreateFileChooserUsingJFileChooser cfcujfc=new CreateFileChooserUsingJFileChooser();
}
}


************************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************************
Related Posts Plugin for WordPress, Blogger...