How to use JFileChooser to find a file location

放肆的年华 提交于 2019-12-19 10:58:53

问题


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?


回答1:


The example in the javadoc show show to do this:

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.




回答2:


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.




回答3:


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.

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);


来源:https://stackoverflow.com/questions/18774652/how-to-use-jfilechooser-to-find-a-file-location

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