JFileChooser on a Button Click

2019-07-02 00:34发布

问题:

I have a button, clicking on which I want the JFileChooser to pop up. I have tried this

JButton browse= new JButton("Browse");
add(browse);
browse.addActionListener(new ClassBrowse());

public class ClassBrowse implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
              // return the file path 
            } catch (Exception ex) {
              System.out.println("problem accessing file"+file.getAbsolutePath());
            }
        } 
        else {
            System.out.println("File access cancelled by user.");
        }       
    }   
}

Bhe above gives error The method showOpenDialog(Component) in the type JFileChooser is not applicable for the arguments (ClassName.ClassBrowse)

Also, I want it to return the complete file path. How do I do so ?

回答1:

  1. ActionListener is not a Component, you can't pass this to the file chooser.
  2. You could look at File#getCanonicalPath to get the full path of the file, but you can't return it, as actionPerformed only returns a void (or no return type). You could, however, set some other variable, call another method or even set the text of a JLabel or JTextField ... for example...


回答2:

You can set a instance variable which holds the file name string in the actionPerformed such as

private String fileName;
.......
your code
.......
public void actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog((Component)e.getSource());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        try {
           fileName = file.toString();
        } catch (Exception ex) {
          System.out.println("problem accessing file"+file.getAbsolutePath());
        }
    } 
    else {
        System.out.println("File access cancelled by user.");
    }       
}   


回答3:

You can pass the container (It might be a JFrame, JDialog, JApplet or any) your JButton lies in to the

fileChooser.showOpenDialog()

and the filechooser will open as a modal dialog on top of that container.