launching and closing a native browser that points to web app

為{幸葍}努か 提交于 2019-12-01 13:11:44

Here is a piece of code just FYI. You can fork native browser in a process and return a java Process object to your java code. You can invoke the processObject.waitFor() method to wait for the invoked process to terminates.

The Launcher :

public class Launcher implements Runnable {

    public void run() {
        Process p;
        try {
            p = Runtime.getRuntime().exec("notepad.exe");
            p.waitFor();

            // Do something after the forked process terminates
            System.out.println("The browser is exit");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The main class:

public class TestProcess {

    public static void main(String[] args) throws Exception {
        new Thread(new Launcher()).run();
    }

}

Ok, I have managed to find what I am looking for, so I am posting my findings here for anyone who might find this info useful. There are simply 2 solutions that I could use:

  1. There is something called 'BareBoneBrowser' check out the project link here

    this project allows you to launch the user's default browser on any platform (windows, Mac OS, linux) which is exactly what I wanted. and I have tried it and it seems to be working fine. There are few limitations to it (you can't detect if that browser windows has been closed by the user. Maybe there is a way if you have time to understand the code and alter it) but its a quick way to get a browser launched with Java and at the same time being cross platform.

  2. The other solution that I found is the DJ Project click here for project home page

    This is almost a complete solution that allows you to open a 'native' browser in a JPanel. Cross platform (works for Windows and Mac OS or even Linux). Because the browser gets launched inside a JPanel, you can detect when the user 'close' the JPanel and terminates the application so you can then do what ever you need to do to shutdown/terminate or stop your application and doing any cleanup work required.

Hope that this will help anyone who is looking to do something similar. My advice is to just download the code and start playing with it or do a small POC (Proof Of Concept) project to get a better understanding about the API.

Cheers.

Try this

java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));

URL--//your url

it will open the default browser. Hope it works of other OS.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!