[英]Creating a static class to open a new window in Java FXML
我正在開發一個項目,其中有很多窗口被打開和關閉,並且想要創建一個靜態類,它只接受一些參數,然后完成剩下的工作。
問題是“控制器”需要是不同類型的聲明,具體取決於所需的控制器。 例如; FXMLControllerAdd
或FXMLControllerHome
。
我試圖用參數將類型傳遞給方法。 這不起作用,也沒有使用var作為聲明(它在Java11中編碼)因為那時我在下一行有一個“找不到符號”-error for initData()。
public static void nySide(Class c, String controllerPath, Dataset dataset, String tittel, Window window) {
try {
FXMLLoader loader = new FXMLLoader(c.getResource(controllerPath));
Parent root = (Parent) loader.load();
//THIS IS WHERE TO PROBLEM IS
FXMLControllerAdd controller = loader.getController();
controller.initData(dataset);
//This line gets the Stage information
Stage st = new Stage();
st.setTitle(tittel);
st.setScene(new Scene(root));
st.show();
Stage stage = (Stage) window;
stage.close();
} catch (Exception e) {
e.printStackTrace();
}
}
也; 它是否存在需要較少參數的另一種方式?
我想通了Slaw。 制作一個接口Eg(FXMLInitData)並在每個FXMLController.java中實現它,並將該控制器聲明為該接口。
接口:
public interface FXMLInitData {
public void initData(Dataset dataset);
}
方法:
public static void nySide(Class c, String controllerPath, Dataset dataset, String tittel, Window window){
try {
FXMLLoader loader = new FXMLLoader(c.getResource(controllerPath));
Parent root = (Parent) loader.load();
FXMLInitData controller = loader.getController();
controller.initData(dataset);
//This line gets the Stage information
Stage st = new Stage();
st.setTitle(tittel);
st.setScene(new Scene(root));
st.show();
Stage stage = (Stage) window;
stage.close();
} catch (Exception e) {
e.printStackTrace();
}
}
類:
public class FXMLControllerHome implements Initializable, FXMLInitData{
@Override
public void initData(Dataset dataset){
}
}
嘗試讓每個控制器擴展或實現父級Controller。 使父Controller成為參數,並在調用方法而不是String controllerPath
時將子控制器作為參數傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.