I have a Gui with several different classes which uses the same eventhandler. A problem I can't seem to find a solution to is how to avoid getting a nullpointerexception when the eventhandler is looking for the right method call and stumbles upon a button that is yet to be initialized. I have a couple of buttons that will only be initialized when the user goes into a createAccountGui stage.
public class GuiHandler implements EventHandler<ActionEvent> {
// this class take care off the EventHandler (buttons, all the buttons method).
private UserGui uG;
private AdvSearch aS;
private LogIn logI;
private CreateAccGui cAG;
private OrganizerGui oG;
private AdminGui aG;
private PersonRegister pR;
public GuiHandler() {
uG = new UserGui(this);
}
Unless CreateAccGui has been initialized, whenever it comes to the cAG.getRegistrate() I get a nullpointerexception. Does anyone have a smart way of handling this sort of problem without having to split it into several different handlers.
@Override
public void handle(ActionEvent e) {
try {
//where all the button goes 2 when clicked on and perform the method they are supposed 2 do
// UserGui class buttons
if(e.getSource() == uG.getLogInB()) {
logI = new LogIn(this);
} else if (e.getSource() == uG.getAdvSearch()) {
aS = new AdvSearch(this);
} else if (e.getSource() == uG.getSearch()) {
}
// the buttons in LogIn class
else if(e.getSource() == logI.getSignIn()) {
signIn();
} else if(e.getSource() == logI.getCreateAcc()) {
logI.logInStage.close();
cAG = new CreateAccGui(this);
}
//the buttons in CreateAccGui class
else if(e.getSource() == cAG.getRegistrate()) {
System.out.println("it stop here on registrate");
createAccount();
} else if(e.getSource() == cAG.getCancelReg()) {
cAG.getCreateStage().close();
logI = new LogIn(this);
}
//the buttons in AdminGui for setting text from the admin field 2 the userGui
else if(e.getSource() == aG.getAdmLogout()) {
aG.stage.close();
} else if(e.getSource() == aG.getHomeAreaButton()) {
uG.getHomeNews().setText(aG.getHomeArea().getText());
} else if(e.getSource() == aG.getAboutButton()) {
uG.getAboutArea().setText(aG.getAboutArea().getText());
} else if(e.getSource() == aG.getRentButton()) {
uG.getRentArea().setText(aG.getRentArea().getText());
}
} catch(NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Feil format på noen felter, gjerne endre på dem", "Nummer Format", JOptionPane.ERROR_MESSAGE);
}
} // End of Handler method
}// End of GuiHandler class