File pickers like FileDialog only return the name of the file that the user picked. *You* have to write the code that figures out what to do with the selected file.
Here's code that uses Desktop.getDesktop().open() to ask the operating system to launch the default program with the selected file. Note the added imports at the top and the required exception handling try/catch.
- Code: Select all
import java.awt.*;
import java.io.File;
import java.io.IOException;
public class UseFileDialog {
public String loadFile (Frame f, String title, String defDir, String fileType) {
FileDialog fd = new FileDialog(f, title, FileDialog.LOAD);
fd.setFile(fileType);
fd.setDirectory(defDir);
fd.setLocation(50, 50);
fd.setVisible(true);
return fd.getDirectory()+fd.getFile();
}
/*public String saveFile(Frame f, String title, String defDir, String fileType) {
FileDialog fd = new FileDialog(f, title, FileDialog.SAVE);
fd.setFile(fileType);
fd.setDirectory(defDir);
fd.setLocation(50, 50);
fd.setVisible(true);
return fd.getFile();
}*/
public static void main(String s[]) {
UseFileDialog ufd = new UseFileDialog();
//File dialogs only return the filename that the user picked
String filename = ufd.loadFile(new Frame(), "Open...", ".\\", ".");
//Convert it to a File - need to import java.io
File picked_file = new File(filename);
//Print out the message
System.out.println("Loading : "+ filename);//.java allows only .java files
//Ask the operating system to open the specified file using
//whatever the default assigned program is.
try {
Desktop.getDesktop().open(picked_file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("Saving : "+ ufd.saveFile(new Frame(), "Save...", ".\\", "."));
System.exit(0);
}
}