Programmer
Programmer

Reputation: 6753

Making a dialog box that allows user to select file

I want to make a button in Java such that when user clicks it a box opens that allows the user to select a file. Note: For my application , I only need the file path. I do not need the exact file. Is there a way to do this in Java using swing etc

Upvotes: 1

Views: 4638

Answers (2)

sagar chaudhari
sagar chaudhari

Reputation: 1

'private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
    int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
        try {
              // What to do with the file, e.g. display it in a TextArea
            textarea.read( new FileReader( file.getAbsolutePath() ), null );
            } catch (IOException ex) {
                  System.out.println("problem accessing file"+file.getAbsolutePath());
            }
        } else {
            System.out.println("File access cancelled by user.");
        }
}'

Upvotes: 0

Shashank Kadne
Shashank Kadne

Reputation: 8101

Use JFileChooser. Write following code inside your actionPerformed for the Button.

JFileChooser jfc = new JFileChooser();
    jfc.showDialog(null,"Please Select the File");
    jfc.setVisible(true);
    File filename = jfc.getSelectedFile();
    System.out.println("File name "+filename.getName());

Upvotes: 4

Related Questions