Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尝试实现在单击菜单栏项时打开的链接,但出现错误_Java_Javafx - Fatal编程技术网

Java 尝试实现在单击菜单栏项时打开的链接,但出现错误

Java 尝试实现在单击菜单栏项时打开的链接,但出现错误,java,javafx,Java,Javafx,使用主机服务 我正在使用构造函数 HostServices services = this.getHostServices(); 我想让它与以下菜单项一起工作,这样当单击该菜单项时,它会打开指向web浏览器的链接。。。 我希望对象服务处理的代码是 MenuItem fbMenuItem = new MenuItem("Facebook Page"); fbMenuItem.setId("fbMenuItem"); fbMenuItem.setOnAction(event -&g

使用主机服务

我正在使用构造函数

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

但是,当我用菜单栏中没有的普通按钮尝试相同的过程时,效果很好,但是当我在菜单栏上使用上面的技巧时,它仍然会给我这个错误

处理这个问题的一种方法是创建一个单例来保存这些类型的引用,然后在应用程序启动时实例化它

例如:

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");

. 只能在扩展Application.OK的类中调用此.getHostServices(),那么,我如何制作一种链接按钮,单击该按钮将打开web浏览器,但该按钮将作为菜单项位于菜单栏中。您可以将HostServices对象传递给您的
Caesar
类的构造函数。但是HostServices不适用于不扩展应用程序的类。我将在哪里声明该构造函数?直截了当。通过getHostServices()方法检索HostServices对象只适用于扩展应用程序的类。HostServices对象本身可以在任何地方工作。Ok将尝试并给出反馈