Search code examples
javamacosjavafxfile-association

Desktop.setOpenFileHandler doesn't work when program isn't running


I'm making a program for mac that has it's own file extension .edul. I got it working so that when the program has already opened and you open the file it's load it, but when I try this when the program is yet running I don't get the event and it's not in the args.

I tried to change to com.apple.eawt.Application but unfortunately java.desktop doesn't export this class so this didn't work.

Desktop desktop = Desktop.getDesktop();
desktop.setOpenFileHandler(e -> {
    try {
        FileWriter fileWriter = new FileWriter(System.getProperty("user.home") + "/Desktop/test.txt");
        fileWriter.write(e.getFiles().toString());
        fileWriter.close();
    } catch (IOException ignored) {
    }
});

So I expect a file on my desktop that has the location of the file I opened before the program was running and when it's running and I open another file it's also shows on my desktop.

So after first file open: [file/path/test.edul]

And on seconds file open: [file/path/test2.edul]

I'm currently only getting: [file/path/test2.edul]


Solution

  • So, the problem is that when you define a FileOpenHandler in the class which starts your fx application the FileOpenEvent is only thrown when the program is already running. So you should make a other main class that doesn't extends Application and the FileOpenEvent will be correctly thrown even when the application is still starting up.