私はJavaを使い慣れていないため、オブジェクトを理解するための助けが必要です。私はjavaFxでアプリケーションを作成しようとしていますが、ウィンドウ間でオブジェクトを渡すのに問題があります。現在、ログインウィンドウがあります。データベースを確認してログインの詳細が正しい場合は、ダッシュボードウィンドウが開きます。しかし、ダッシュボードウィンドウのログインボタンを押して、BackendInterface
クラスからメソッドを呼び出すときに作成したばかりのオブジェクトBackendInterface
が必要になります。私が今はnullポインタの例外を与えている。 this.backendInterface
を渡しLoginController
クラスにコンストラクタを追加JavaFXのウィンドウ間でオブジェクトを渡す方法
は、だから私の質問は、あなたが、それは方法の使用には、別のウィンドウにオブジェクトのインスタンスを渡すんですかFXML負荷例外
が得?ダッシュボード上のボタンの
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 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 DashboardController {
@FXML
public void doStuff(){
LoginController loginController = new LoginController();
loginController.backendInterface.printSomething();
}
}
UPDATED SOLUTION 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);
前記第二のコントローラオブジェクトを渡すには、あなたはその1とは何の関係もありませんあなたのDashboardController
で新しいLoginController
を作成しているオブジェクトのメソッド
public void setBackendInterface(BackendInterface backendInterface) {
this.backendInterface = backendInterface;
}