Opening URL in a browser from JavaFX Desktop Application

使用JavaFX和自定义类在桌面应用中打开浏览器窗口
本文介绍了如何在JavaFX桌面应用程序中使用自定义类UrlOpener来打开浏览器窗口,通过Hyperlink控件或文本框控制输入URL。详细解释了在Eclipse和NetBeans中遇到的问题及解决方案。

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

http://blogs.sun.com/sanaulla/entry/opening_browser_from_javafx_desktop

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值