JavaFX Freeze on Desktop.open(file), Desktop.browse(uri)

北城余情 提交于 2019-11-28 09:01:26

I also had the same problem and this solution works for me:

if( Desktop.isDesktopSupported() )
{
    new Thread(() -> {
           try {
               Desktop.getDesktop().browse( new URI( "http://..." ) );
           } catch (IOException | URISyntaxException e1) {
               e1.printStackTrace();
           }
       }).start();
}

I resolved problem with...

 public static void abrirArquivo(File arquivo) {
    if (arquivo != null) {
        if (arquivo.exists()) {
            OpenFile openFile = new OpenFile(arquivo);
            Thread threadOpenFile = new Thread(openFile);
            threadOpenFile.start();
        }
    }
}

private static class OpenFile implements Runnable {

    private File arquivo;

    public OpenFile(File arquivo) {
        this.arquivo = arquivo;
    }

    private void abrirArquivo(File arquivo) throws IOException {

        if (arquivo != null) {
            java.awt.Desktop.getDesktop().open(arquivo);
        }

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            abrirArquivo(arquivo);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

I also have this same problem. I found out that if I call the Desktop.open() method from a new thread, the file will open after I close the JavaFX application window, but that doesn't help much.

If you put

SwingUtilities.invokeLater(() -> System.out.println("Hello world"));

in to your main method after your launch(args) call, it also won't get called until after you close the JavaFX application.

It seems like there's some kind of concurrency issue between the JavaFX application and Swing.

On Ubuntu you can try

xdg-open filename

from your JavaFX app.

As far as I can tell, your code should work.

There is a new way to handle this in JavaFX. The only downside I see is you need to instantiate a HostServicesDelegate using the Application singleton.

HostServicesDelegate hostServices = HostServicesFactory.getInstance(appInstance);
hostServices.showDocument("http://www.google.com");

Encapsulate it on a System thread:

    final String url = "www.google.com";
    final Hyperlink hyperlink = new Hyperlink("Click me");
        hyperlink.setOnAction(event -> new Thread(() -> {
            try {
                Desktop.getDesktop().browse(new URI(url));
            } catch (IOException | URISyntaxException e1) {
                e1.printStackTrace();
            }
        }).start());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!