So I'm working on a password management application and it is my first attempt at a GUI in Java. I the application to close the login window once the user has clicked the Login button and just display the main application window. Whenever I try to do so my setPrevStage
method is storing a NULL value and the prevStage.close()
method causes the program to crash with a NullPointerException. Not sure what I am doing wrong so any advice is greatly appreciated. Here is my .java file for this operation.
package pwmanager;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
/**
*
* @author 176878
*/
public class FXMLDocumentController implements Initializable {
@FXML
private Button loginButton;
@FXML
Stage prevStage;
Stage currentStage;
public void setPrevStage(Stage stage){
prevStage = stage;
if (stage == null){
System.out.println("Stage NULL");
}
}
@FXML
public void getPrevStage(Stage stage){
currentStage = prevStage;
}
@FXML
public void loginButtonAction(ActionEvent event) throws IOException {
System.out.println("You clicked me, logging in!");
setPrevStage(prevStage);
Stage stage = new Stage();
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainScreen.fxml"));
Parent mainScreen = (Parent)loader.load();
Scene scene = new Scene(mainScreen);
stage.setScene(scene);
stage.setTitle("Password Manager");
prevStage.close();
stage.show();
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
if in prevStage there is the "old" stage then you try it:
If not ... in your Start.class you define static Stage stage and set in this your primarystage read this example:
and the code is now this: