Grumblesaurus
Grumblesaurus

Reputation: 3119

JavaFX and and getDesktop().open() crashes the program

When I try to call Desktop.getDesktop().open(), my program crashes.

I'm on Ubuntu GNOME 16.10, running Gnome 3.20.4. I haven't had a chance to test this code on another platform, but on this platform it is definitely crashing the program.

browseMenuItem.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {

        Platform.runLater( new Runnable() {
            public void run() {
                try {
                    System.out.println ( Desktop.isDesktopSupported() );
                    Desktop.getDesktop().open( albumTable.getSelectionModel().getSelectedItem().getPath().toFile() );
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
});

Any thoughts on how to fix or troubleshoot this?

Upvotes: 0

Views: 799

Answers (2)

Grumblesaurus
Grumblesaurus

Reputation: 3119

It looks like @James_D's answer is the better way to do things, but currently (as of 2017/05/03) it doesn't work on the OpenJDK / OpenJFK.

Thankfully, his comment about mixing JFX and Swing helped me find a solution which will work on OpenJDK / OpenJFX:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        try {
            Desktop.getDesktop().open( albumTable.getSelectionModel().getSelectedItem().getPath().toFile() );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});

The trick was using SwingUtilities.invokeLater() rather than Platform.runLater(), since the code inside is swing.

Upvotes: 0

James_D
James_D

Reputation: 209418

You're mixing JavaFX and AWT, which is likely causing the problem. Instead of

Desktop.getDesktop().open(file);

try using the JavaFX API:

getHostServices().showDocument(file.toURI().toString());

getHostServices() is defined in Application (so you may need to retrieve it in your start method and pass it to whichever object - perhaps a controller - is registering the listener with the menu item).

Upvotes: 4

Related Questions