Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open Browser window from Java program

Question

I have an application written in Java. It is designed to run on a Linux box standalone. I am trying to spawn a new firefox window. However, firefox never opens. It always has a shell exit code of 1. I can run this same code with gnome-terminal and it opens fine.

Background

So, here is its initialization process:

  1. Start X "Xorg :1 -br -terminate -dpms -quiet vt7"
  2. Start Window Manager "metacity --display=:1 --replace"
  3. Configure resources "xrdb -merge /etc/X11/Xresources"
  4. Become a daemon and disconnect from controlling terminal

Once the program is up an running, there is a button the user can click that should spawn a firefox window. Here is my code to do that. Remember X is running on display :1.

Code


public boolean openBrowser()
{
  try {
    Process oProc = Runtime.getRuntime().exec( "/usr/bin/firefox --display=:1" );
    int bExit = oProc.waitFor();  // This is always 1 for some reason

    return true;

  } catch ( Exception e ) {
    oLogger.log( Level.WARNING, "Open Browser", e );
    return false;
  }
}
like image 978
Ryan Ayers Avatar asked Oct 29 '08 21:10

Ryan Ayers


2 Answers

If you can narrow it down to Java 6, you can use the desktop API:

http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/

Should look something like:

    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.BROWSE)) {
            try {
                desktop.browse(new URI("http://localhost"));
            }
            catch(IOException ioe) {
                ioe.printStackTrace();
            }
            catch(URISyntaxException use) {
                use.printStackTrace();
            }
        }
    }
like image 72
James Van Huis Avatar answered Oct 06 '22 01:10

James Van Huis


Use BrowserLauncher.

Invoking it is very easy, just go

new BrowserLauncher().openURLinBrowser("http://www.google.com");
like image 38
Zarkonnen Avatar answered Oct 06 '22 01:10

Zarkonnen