Java Swing File Chooser Example using JFileChooser in JFrame
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
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(); } } |