[英]How to call all of the methods of a class in a method of another class in java
我正在設計JavaFX應用程序,需要在另一個窗口的Controller中調用其中一個窗口的Application類。
MainController.java:
public class MainController {
@FXML
public Button buttonLogin;
@FXML
public Button buttonNeuAnmelden;
@FXML
public void handleButtonLoginAction(ActionEvent event) {
((Node) (event.getSource())).getScene().getWindow().hide();
System.out.println("LoginButton geclickt!");
}
@FXML
public void handleButtonNeuAnmeldenAction(ActionEvent event) {
((Node) (event.getSource())).getScene().getWindow().hide();
System.out.println("NeuAnmeldenButton Geclickt!");
}
}
LoginApp.java:
public class LoginApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(
getClass().getResource("/design/Login.fxml"));
Parent root = loader.load();
primaryStage.setTitle("Benutzerverwaltung");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
我特別需要運行LoginApp
所有方法,這意味着handleButtonLoginAction()
方法中的main(String[] args)
和start(Stage primaryStage)
類,就好像在該時刻正好調用了整個類一樣。
我該怎么做呢?
如果我正確理解了這個問題,則需要對它進行大量重構。 定義一個獨立於您的Application
子類的LoginView
類:
public class LoginView {
private final Stage displayStage ;
private final Scene scene ;
public LoginView(Stage displayStage) throws IOException {
this.displayStage = displayStage ;
FXMLLoader loader = new FXMLLoader(
getClass().getResource("/design/Login.fxml"));
Parent root = loader.load();
scene = new Scene(root);
displayStage.setScene(scene);
displayStage.setTitle("Benutzerverwaltung");
}
public LoginView() throws IOException {
this(new Stage());
}
public void show() {
displayStage.show();
}
public void hide() {
displayStage.hide();
}
// ...
}
然后您的Application
類如下所示:
public class LoginApp extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
LoginView loginView = new LoginView(primaryStage);
// ...
loginView.show();
}
}
您的問題沒有顯示MainController
與應用程序之間的關系,但是您需要做的就是loginView
您創建的loginView
的引用傳遞給MainController
,然后從MainController
的方法調用loginView.show()
。
如果您不想重構您的軟件體系結構,則可以嘗試Reflection ,並執行以下操作:
public static Method[] getAccessibleMethods(Class clazz) {
List<Method> result = new ArrayList<Method>();
while (clazz != null) {
for (Method method : clazz.getDeclaredMethods()) {
int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
result.add(method);
}
}
clazz = clazz.getSuperclass();
}
return result.toArray(new Method[result.size()]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.