Java 如何使用 JFileChooser 查找文件位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18774652/
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
How to use JFileChooser to find a file location
提问by Stefan Carlson
Is there a method that i can use to simply find a file location? I'm trying allow the user to choose a file and open it, but I have to have the JFileChooser just choose the file and send the location to another method. What's the best way to do this?
有没有一种方法可以用来简单地查找文件位置?我正在尝试允许用户选择一个文件并打开它,但我必须让 JFileChooser 只选择文件并将位置发送到另一种方法。做到这一点的最佳方法是什么?
采纳答案by Daniel Kaplan
The example in the javadocshow show to do this:
javadocshow 中的示例显示执行此操作:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
That's what chooser.getSelectedFile()
is doing. Take the result of that and pass it to another method.
这就是chooser.getSelectedFile()
正在做的事情。获取结果并将其传递给另一个方法。
回答by JNL
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// You can use
// chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); too
File file = chooser.getSelectedFile();
String fullPath = file.getAbsolutePath();
Then Pass the String to the other method.
然后将字符串传递给另一个方法。
回答by Fridjato Part Fridjat
We can also use TextArea to get paths of any file example here for Image File and the name of object TextArea is txtPath, and we make ActionPerformed to JButton named bChoose with the folowing method.
我们还可以使用TextArea 来获取Image File 的任何文件示例的路径,对象TextArea 的名称为txtPath,我们使用以下方法将ActionPerformed 设置为名为bChoose 的JButton。
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "gif");
fc.setFileFilter(filter);
fc.showDialog(bChoose, "Choose File");
String strPath = txtPath.getText() + "\n" + fc.getSelectedFile().toString();
txtPath.setText(strPath);