1

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?

MadukaJ
  • 722
  • 6
  • 22
Stefan Carlson
  • 372
  • 3
  • 7
  • 21
  • I don't understand your question. You want to "...simply find a file location..."? You want to "...allow the user to choose a file..."? But you have to have a JFileChooser? A JFileChooser is a good way to let a user choose a file. One thing that can make it easier for the user is to specify a directory for the JFileChooser to begin with. If you want to do your own dialog to let the user choose a file, you could have a JList in a JDialog and you could add the file names to the JList in your own code. I'm not sure exactly what you're asking though. However you get it, use a File object.. – Kaydell Sep 14 '13 at 01:03

3 Answers3

5

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.

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
3
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.

JNL
  • 4,683
  • 18
  • 29
  • Why not pass the File reference? It has many useful methods associated with the file system, just saying – MadProgrammer Sep 12 '13 at 21:51
  • @MadProgrammer Agree. OP had asked to send about the location. So just gave the OP a way to do it. – JNL Sep 12 '13 at 21:53
0

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