java 按钮单击时的 JFileChooser
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16351875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JFileChooser on a Button Click
提问by OneMoreError
I have a button, clicking on which I want the JFileChooser to pop up. I have tried this
我有一个按钮,单击它我希望 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.");
}
}
}
Bhe above gives error The method showOpenDialog(Component) in the type JFileChooser is not applicable for the arguments (ClassName.ClassBrowse)
Bhe上面给出了错误 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 ?
另外,我希望它返回完整的文件路径。我该怎么做?
回答by MadProgrammer
ActionListener
is not aComponent
, you can't passthis
to the file chooser.- You could look at
File#getCanonicalPath
to get the full path of the file, but you can'treturn
it, asactionPerformed
only returns avoid
(or no return type). You could, however, set some other variable, call another method or even set the text of aJLabel
orJTextField
... for example...
ActionListener
不是Component
,您无法传递this
给文件选择器。- 您可以查看
File#getCanonicalPath
获取文件的完整路径,但您不能这样return
做,因为actionPerformed
只返回一个void
(或没有返回类型)。但是,您可以设置一些其他变量,调用其他方法,甚至设置 aJLabel
或JTextField
...的文本,例如...
回答by prasanth
You can set a instance variable which holds the file name string in the actionPerformed such as
您可以在 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.");
}
}
回答by Thudani Hettimulla
You can pass the container (It might be a JFrame, JDialog, JApplet or any) your JButton lies in to the
您可以将 JButton 所在的容器(可能是 JFrame、JDialog、JApplet 或任何)传递给
fileChooser.showOpenDialog()
fileChooser.showOpenDialog()
and the filechooser will open as a modal dialog on top of that container.
并且文件选择器将作为该容器顶部的模式对话框打开。