Java JFileChooser

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java JFileChooser

The object of JFileChooser class represents a dialog window from which the user can select file. It inherits JComponent class.

JFileChooser class declaration

Let's see the declaration for javax.swing.JFileChooser class.

  1. public class JFileChooser extends JComponent implements Accessible  

Commonly used Constructors:

Constructor

Description

JFileChooser()

Constructs a JFileChooser pointing to the user's default directory.

JFileChooser(File currentDirectory)

Constructs a JFileChooser using the given File as the path.

JFileChooser(String currentDirectoryPath)

Constructs a JFileChooser using the given path.

Java JFileChooser Example

  1. import javax.swing.*;    
  2. import java.awt.event.*;    
  3. import java.io.*;    
  4. public class FileChooserExample extends JFrame implements ActionListener{    
  5. JMenuBar mb;    
  6. JMenu file;    
  7. JMenuItem open;    
  8. JTextArea ta;    
  9. FileChooserExample(){    
  10. open=new JMenuItem("Open File");    
  11. open.addActionListener(this);            
  12. file=new JMenu("File");    
  13. file.add(open);             
  14. mb=new JMenuBar();    
  15. mb.setBounds(0,0,800,20);    
  16. mb.add(file);              
  17. ta=new JTextArea(800,800);    
  18. ta.setBounds(0,20,800,800);              
  19. add(mb);    
  20. add(ta);              
  21. }    
  22. public void actionPerformed(ActionEvent e) {    
  23. if(e.getSource()==open){    
  24.     JFileChooser fc=new JFileChooser();    
  25.     int i=fc.showOpenDialog(this);    
  26.     if(i==JFileChooser.APPROVE_OPTION){    
  27.         File f=fc.getSelectedFile();    
  28.         String filepath=f.getPath();    
  29.         try{  
  30.         BufferedReader br=new BufferedReader(new FileReader(filepath));    
  31.         String s1="",s2="";                         
  32.         while((s1=br.readLine())!=null){    
  33.         s2+=s1+" ";    
  34.         }    
  35.         ta.setText(s2);    
  36.         br.close();    
  37.         }catch (Exception ex) {ex.printStackTrace();  }                 
  38.     }    
  39. }    
  40. }          
  41. public static void main(String[] args) {    
  42.     FileChooserExample om=new FileChooserExample();    
  43.              om.setSize(500,500);    
  44.              om.setLayout(null);    
  45.              om.setVisible(true);    
  46.              om.setDefaultCloseOperation(EXIT_ON_CLOSE);    
  47. }    
  48. }  

Output:

Java Jfilechooser 1