Showing File Browser and Message Box using Java Swing

Post date: Mar 23, 2011 9:41:32 AM

Syntax:

/Create a file chooser

final JFileChooser fc = new JFileChooser();

...

//In response to a button click:

int returnVal = fc.showOpenDialog(aComponent);

int returnVal = fc.showDialog(FileChooserDemo2.this, "Attach");

Example Program:

private void btnProjectBrowseActionPerformed(ActionEvent e) {

            // TODO add your code here

           JFileChooser fileChooser=new JFileChooser();

            //Get Selected File

            int returnValue=0;

            //For select the project file

            int selectValue=JFileChooser.APPROVE_OPTION;           

            while(selectValue== JFileChooser.APPROVE_OPTION){ 

                  //Show the File Open Dialog box               

                  returnValue = fileChooser.showOpenDialog(this);                 

                  //Return 1 if file is selected

                  if(returnValue == JFileChooser.APPROVE_OPTION){                                                    //Get selected file

                        selectedFile= fileChooser.getSelectedFile();

                         //Show the selected path into the Text box.

                            txtProjectPath.setText(selectedFile.getPath());

                                                         //Break the while loop

                             break;                       

                        }

                        else{

                              //File not selected means

                              txtProjectPath.setText("");

                                                     //Showing the Message box

                              selectValue=JOptionPane.showConfirmDialog(this, "Please Select JAR, WAR,JAVA or ZIP files!","Oops Wrong File!",JOptionPane.OK_OPTION,JOptionPane.ERROR_MESSAGE);                     

                    }

  }