簡體   English   中英

非靜態方法getHostServices()不能從靜態上下文中引用

[英]non-static method getHostServices() cannot be referenced from a static context

我有這個調用電子郵件客戶端的JavaFX代碼

        MenuItem ri = new MenuItem("Report Issue");

        // Start E-Mail Client with E-Mail template and send E-Mail
        ri.setOnAction(new EventHandler<ActionEvent>()
        {
            @Override
            public void handle(ActionEvent e)
            {


                Application.getHostServices().showDocument("mailto:"+textField.getText());



            }
        });

我在Netbeans non-static method getHostServices() cannot be referenced from a static context獲取消息non-static method getHostServices() cannot be referenced from a static context

你能告訴我怎么解決這個問題嗎?

PS這是我可以創建的解決方案:

ri.setOnAction(new EventHandler<ActionEvent>()
        {
            @Override
            public void handle(ActionEvent e)
            {

                Application a = new Application() {

                    @Override
                    public void start(Stage stage)
                    {
                    }
                };
                final TextField textField = new TextField("help@example.com");
                a.getHostServices().showDocument("mailto:"+textField.getText());

            }
        });

有更好的建議嗎?

看起來像getHostServices()不是Application類或其子類中定義的靜態方法。

我以這種方式使用代碼:

public class App extends Application {
    private static App mInstance;
    public static void main(String[] args) throws Exception { launch(args); }

    public static App getInstance() {
        return mInstance;
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        // your code
    }
}

你可以在你的應用程序中的任何地方得到它

HostServices services = App.getInstance().getHostServices();
services.showDocument(url);

最好的方法是實例化您的Application類以在非靜態上下文中使用該方法:

應用a = new Application();
。a.getHostServices()showDocument( “電子郵件地址:” + textField.getText());

或者如果要在靜態上下文中運行此程序,請更改getHostServices()方法:

public void getHostServices(){...}
喜歡的東西
public static void getHostServices(){...}

(編輯)詹姆斯指出我的回答是FX的無稽之談; 你不能修改應用程序,並且實例化沒有任何意義。 如果您的程序擴展了Application,那么嘗試簡單地刪除“Application”。 從您的第一個代碼開始,因為您的程序繼承了getHostServices()方法。

如果它適合您的設計,那么可以使getHostServices成為靜態方法,或者安排從非靜態方法或塊中調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM