2016-11-20 111 views
0

我有一個Utility類,其中我試圖創建一個名爲switchScenestatic方法,以便能夠輕鬆切換場景中的場景。這是我嘗試使用代碼:JavaFX問題切換場景

public class Utility { 
    public static void switchScene(String path) { 
     Stage stage = getMainStage(); // Assume this returns the primary stage 
     FXMLLoader loader = new FXMLLoader(); 
     loader.setLocation(getClass().getResource(path)); 

     try { 
      Parent root = loader.load(); 
      Controller controller = loader.getController(); 
      controller.start(); 
      Scene scene = new Scene(root); 
      stage.setScene(scene); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

我想這個代碼將工作(我正在盡一切控制器我認爲實現Controller接口,只是上有一個start方法),但是我得到此錯誤消息:

java: non-static method getClass() cannot be referenced from a static context 

有什麼我可以做些什麼來解決這個問題?

回答

1

不要路徑作爲String。將其更改爲URL

現在,每個人都可以用自己的FXML稱之爲無論它可能是和簽名是關於什麼的說法應該是減少混亂:

Utility.switchScene(SomeClass.class.getResource("someView.fxml")); 

這是不相干的你的問題,但我也建議你將Stage作爲參數或通過依賴注入,而不是調用函數(Inversion of Control principle)並拋出IOException而不是捕獲它,因爲它告訴實用程序類的用戶有關可能出現錯誤的可能方式。我也認爲返回Controller而不是返回void是一個不錯的主意,以便用戶可以使用它。

+0

非常感謝,特別是關於使用良好做法的提示! – saadq

+0

不客氣。我很高興它有幫助。 – Omid

2

如果你想打電話getClass()static方法,你需要使用它與類名一起,所以你需要改變你的代碼如下所示:

loader.setLocation(Utility.class.getClass().getResource(path)); 
+0

嗯,這肯定會使錯誤消失,但它似乎並不像這樣,它說'java.lang.IllegalStateException:Location is not set.'這是一個我不能抽象這個代碼的情況這個單獨的'Utility'類? – saadq

+0

你有'路徑'變量設置正確嗎? – developer