JFileChooser on a Button Click

旧城冷巷雨未停 提交于 2019-12-12 13:16:00

问题


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.



来源:https://stackoverflow.com/questions/16351875/jfilechooser-on-a-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!