我是新來的Java和需要幫助理解的對象。我試圖在javaFx中創建應用程序,但無法在窗口之間傳遞對象。目前有一個登錄窗口,如果通過檢查數據庫登錄詳細信息是正確的,儀表板窗口將打開。但是,現在我需要在儀表板窗口中按登錄按鈕以調用BackendInterface
類中的方法時創建的BackendInterface
對象。我現在擁有一個空指針異常。如何通過窗口之間的對象JavaFX中
添加一個構造函數的LoginController
類通過this.backendInterface
產生一個FXML負載例外
所以我的問題是你如何通過一個實例化對象到另一個窗口中使用它的方法?
主
public class MainGui extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("login.fxml"));
primaryStage.setTitle("Login");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
的LoginController爲登錄按鈕
public class LoginController {
BackendInterface backendInterface;
@FXML
TextField username;
@FXML
PasswordField password;
@FXML
Button loginButton;
@FXML
Label loginLabel;
@FXML
public void loginButtonPress(){
if (username.getText().isEmpty() == true || password.getText().isEmpty() == true) {
loginLabel.setText("Please enter data in the fields below");
} else {
//initialises backend interface with username and password
backendInterface = new BackendInterface(username.getText(), password.getText().toCharArray());
//opens a connection to the database
backendInterface.openConnection();
if (backendInterface.getConnectionResponse() == "success"){
//return and print response
System.out.println(backendInterface.getConnectionResponse());
//directs the user to the dashboard after successful login
try{
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("dashboard.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.setTitle("Welcome " + username.getText());
stage.setScene(new Scene(root1));
stage.show();
//Closes the login screen window
Stage stage2 = (Stage) loginButton.getScene().getWindow();
stage2.hide();
} catch (Exception e){
e.printStackTrace();
}
} else {
//warns user of invalid login
loginLabel.setText(backendInterface.getConnectionResponse());
}
}
}
}
DashboardController用於按鈕上的儀表板
public class DashboardController {
@FXML
public void doStuff(){
LoginController loginController = new LoginController();
loginController.backendInterface.printSomething();
}
}
更新的解決方案基於Clayns響應:
第一個控制器加載新的頁面,並通過對象
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("dashboard.fxml"));
loader.load();
Parent p = loader.getRoot();
Stage stage = new Stage();
stage.setScene(new Scene(p));
DashboardController dashboardController = loader.getController();
dashboardController.setBackendInterface(backendInterface);
第二個控制器檢索對象的方法
public void setBackendInterface(BackendInterface backendInterface) {
this.backendInterface = backendInterface;
}