单击按钮上的JFileChooser [英] JFileChooser on a Button Click

查看:88
本文介绍了单击按钮上的JFileChooser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,单击要弹出JFileChooser的按钮.我已经尝试过了

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

上述情况给出错误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 ?

推荐答案

您可以设置一个实例变量,该变量在actionPerformed中保存文件名字符串,例如

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

这篇关于单击按钮上的JFileChooser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆