使用HostServices。
我正在使用构造函数
HostServices services = this.getHostServices();
我希望它能够使用以下菜单项,以便在单击该菜单项时,它应该打开指向Web浏览器的链接... 我希望对象服务处理的代码是
MenuItem fbMenuItem = new MenuItem("Facebook Page");
fbMenuItem.setId("fbMenuItem");
fbMenuItem.setOnAction(event -> {
services.showDocument("facebook.com");
});
我已导入
import javafx.application.HostServices;
应该与 HostServices 一起使用,但我一直收到错误消息
Caesar.java:359: error: cannot find symbol
HostServices services = this.getHostServices();
^
symbol: method getHostServices()
1 error
但是当我使用不在menuBar中的普通按钮尝试相同的程序时它工作正常但是当我在menuBar上面使用上面的技巧时它仍然给我错误
答案 0 :(得分:0)
处理此问题的一种方法是创建一个单例来保存这些类型的引用,然后在应用程序启动期间实例化它。
例如:
public class HostServiceWrapper {
private static HostServiceWrapper _instance;
private HostServices hostServices;
private HostServiceWrapper (HostServices hostServices) {
// Do not allow this to be created externally
if (hostServices == null) {
throw new RuntimeException("Host services can't be null to instantiate this method");
}
this.hostServices = hostServices;
}
public static void createInstance(HostServices hostServices) {
if (_instance == null) {
_instance = new HostServiceWrapper (hostServices);
}
}
public static HostServiceWrapper getInstance() {
if (_instance== null) {
throw new RuntimeException("HostServiceWrapper has not been correctly instantiated.");
}
return _instance;
}
public void openURL(String url) {
hostServices.showDocument(url);
}
}
然后在你的应用程序启动方法中你会做这样的事情......
public void start(Stage primaryStage) throws Exception {
.....
HostServiceWrapper.createInstance(getHostServices());
}
然后你需要访问它....
HostServiceWrapper.getInstance().openURL("http://www.google.com");