SAN Adventures

pageicon Saturday Jun 20, 2009

Opening URL in a browser from JavaFX Desktop Application

I searched a bit for opening URL in a browser window using Java and came across the following API:

java.awt.Desktop.getDesktop(new  URI ("www.google.com"  ));

But then when i tried to run the application using this code snippet i got error both in Eclipse 3.4 and in NetBeans 6.5. Eclipse atleast showed the class Desktop in its Intellisense but NetBeans did not do even that. But when i tried to run the same application from the command line it executed with out any exceptions. No idea wat may be the problem. Anyways i figured some way to open a browser using the Hyperlink control of JavaFX. For this i made use of a custom class UrlOpener-

//UrlOpener.java

class UrlOpener{
 public void openURL(String url) throws Exception{
 java.awt.Desktop.getDesktop().browse(new URI(url));
}
}

Now we make use of this helper java class in our JavaFX script hyperlink.fx. This script contains a TextBox control to enter the URL to open. The user can either open the url by clicking on the Hyperlink or by pressing enter from the TextBox control.

//hyperlink.fx

import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.control.*;

var urlBox: TextBox;
var hyperLink: Hyperlink;
Stage {
    title: "HyperLink"
    width: 300
    height: 200
    scene: Scene {
        content: [
            Text{
                content: "Opening a URL Demo"
                translateX: 10
                translateY: 40
                font:Font{
                    size: 15
                }
            },
            Label{
                text: "Enter the URL"
                translateX: 10
                translateY: 70
                width: 100
            },
            urlBox=TextBox{
                translateX: 120
                translateY: 70
                width: 100
                action: function():Void{
                    UrlOpener{}.openURL(urlBox.text);
                }
                
            },
            hyperLink=Hyperlink{
                
                translateY: 100
                width: 200
                text: bind "Visit {urlBox.text}"
                action: function():Void{
                    UrlOpener{}.openURL(urlBox.text);
                }

            }

        ]
    }
} 

The screenshot:

I did not try the Applet version. Also this is not working when tried using NetBeans or Eclipse. Have to figure out why so. If there's an alternate way to open the URL via Hyperlink do let me know. I would be really greatful for that. This particular sample uses TextBox and Hyperlink control