3

我有一个按钮,点击我希望 JFileChooser 弹出。我试过这个

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.");
        }       
    }   
}

上面给出了错误The method showOpenDialog(Component) in the type JFileChooser is not applicable for the arguments (ClassName.ClassBrowse)

另外,我希望它返回完整的文件路径。我该怎么做?

4

3 回答 3

1
  1. ActionListener不是Component,您不能传递this给文件选择器。
  2. 您可以查看File#getCanonicalPath获取文件的完整路径,但不能return,因为actionPerformed只返回一个void(或没有返回类型)。但是,您可以设置其他变量,调用其他方法,甚至设置 aJLabelJTextField... 的文本,例如...
于 2013-05-03T05:05:21.723 回答
1

您可以在 actionPerformed 中设置一个包含文件名字符串的实例变量,例如

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.");
    }       
}   
于 2013-05-03T05:12:13.263 回答
0

您可以将您的 JButton 所在的容器(可能是 JFrame、JDialog、JApplet 或任何)传递给

fileChooser.showOpenDialog()

并且文件选择器将作为该容器顶部的模式对话框打开。

于 2013-05-03T05:56:16.153 回答