我试图在Java中的多个场景之间通过setter方法传递值。但是当我尝试的时候,NullPointerException
就会出现。我想保留电子邮件(用户名)在其他控制器,以及识别用户。这是我的登录代码。
public class Controller {
public JFXTextField newsletterEmail;
public JFXButton regButton;
public JFXTextField loginUserName;
public JFXPasswordField loginPassword;
public JFXButton loginButton;
Connectivity connection = new Connectivity();
Connection connec = connection.getConnection();
SceneSwitcher sceneSwitcher = new SceneSwitcher();
ViewMyAccount viewMyAccount = new ViewMyAccount();
loginValidation validateLogin = new loginValidation();
public void loginButtonClicked(ActionEvent actionEvent) {
System.out.println(loginUserName.getText());
boolean validateCustomer = validateLogin.CusLoginValidate(loginUserName.getText(),loginPassword.getText(),connec);
boolean validateStaff = validateLogin.StaffLoginValidate(loginUserName.getText(),loginPassword.getText(),connec);
boolean validateOwner = validateLogin.OwnerLoginValidate(loginUserName.getText(),loginPassword.getText(),connec);
if(loginUserName.getText().equals("") || loginPassword.getText().equals("")){
AlertBox.displayAlertBox("ERROR!","Both fields can't be empty!");
}else{
if(validateCustomer){
sceneSwitcher.switchScene(loginButton,"customerView.fxml","Customer");
}else if(validateStaff){
sceneSwitcher.switchScene(loginButton,"staffView.fxml","Customer");
}else if(validateOwner){
sceneSwitcher.switchScene(loginButton,"ownerView.fxml","Customer");
}else{
AlertBox.displayAlertBox("ERROR!","Invalid Username or Password! ");
}
}
}
public void registerButtonClicked(ActionEvent actionEvent) {
sceneSwitcher.switchScene(regButton,"register.fxml","Register");
}
NewsletterValidation validateEmail = new NewsletterValidation();
public void newsletterButtonClicked(ActionEvent actionEvent) throws SQLException {
boolean isNewsletterEmailEmpty = validateEmail.invalidError(newsletterEmail);
boolean isValid = validateEmail.isValidEmailAddress(newsletterEmail);
boolean isEmailExist = validateEmail.checkEmailExists(newsletterEmail.getText(),connec);
if(isNewsletterEmailEmpty && isValid && isEmailExist){
PreparedStatement pstmt = null;
String sql = "INSERT INTO `nwemails` (`email`)\n" +
"VALUES (?);";
try {
pstmt = connec.prepareStatement(sql);
pstmt.setString(1,newsletterEmail.getText());
int i = pstmt.executeUpdate();
System.out.println("newsletter email update status = " + i);
AlertBox.displayAlertBox("Alert!","You have successfully signed up for the news letter");
} catch (SQLException e) {
System.err.println(e);
}finally {
pstmt.close();
}
}else{
System.out.println("Validation failed");
}
}
}
这是我的登录屏幕:
我想把这些值传递给这个控制器:
public class ViewMyAccount implements Initializable {
public Label errorPassword;
public Label errorMobile;
public Label errorEmail;
public Label errorLastName;
public Label errorFirstName;
public TextField notes;
public TextField address;
public PasswordField confirmPassword;
public PasswordField password;
public TextField occupation;
public TextField mobile;
public TextField email;
public TextField lastName;
public TextField firstName;
public Button updateButton;
public Button backButton;
Connectivity connection = new Connectivity();
Connection connec = connection.getConnection();
registerValidation validate = new registerValidation();
SceneSwitcher sceneSwitcher = new SceneSwitcher();
public String mail = "mangalika@gmail.com"; //I want the logged in mail to assign this
public void initialize(URL url, ResourceBundle rb) {
//fill info in fields
PreparedStatement pstmtGetInfo = null;
ResultSet rslt = null;
String sqlGetInfo = "SELECT * FROM users WHERE email=?";
System.out.println(mail);
try {
pstmtGetInfo = connec.prepareStatement(sqlGetInfo);
pstmtGetInfo.setString(1,mail);
rslt = pstmtGetInfo.executeQuery();
if(rslt.next()){
StringBuffer stringBuffer1 = new StringBuffer();
stringBuffer1.append(rslt.getString("firstName"));
firstName.setText(stringBuffer1.toString());
StringBuffer stringBuffer2 = new StringBuffer();
stringBuffer2.append(rslt.getString("lastName"));
lastName.setText(stringBuffer2.toString());
StringBuffer stringBuffer3 = new StringBuffer();
stringBuffer3.append(rslt.getString("email"));
email.setText(stringBuffer3.toString());
StringBuffer stringBuffer4 = new StringBuffer();
stringBuffer4.append(rslt.getString("mobile"));
mobile.setText(stringBuffer4.toString());
StringBuffer stringBuffer5 = new StringBuffer();
stringBuffer5.append(rslt.getString("occupation"));
occupation.setText(stringBuffer5.toString());
StringBuffer stringBuffer6 = new StringBuffer();
stringBuffer6.append(rslt.getString("address"));
address.setText(stringBuffer6.toString());
StringBuffer stringBuffer7 = new StringBuffer();
stringBuffer7.append(rslt.getString("password"));
password.setText(stringBuffer7.toString());
confirmPassword.setText(stringBuffer7.toString());
StringBuffer stringBuffer8 = new StringBuffer();
stringBuffer8.append(rslt.getString("notes"));
notes.setText(stringBuffer8.toString());
}else{
System.out.println("no rows for this mail ID");
}
} catch (SQLException e) {
System.err.println(e);
}
}
public void updateButtonClicked(ActionEvent actionEvent) throws SQLException{
boolean isFirstNameEmpty = validate.emptyError(firstName,errorFirstName,"First name is required!");
boolean isFirstNameNum = validate.isNotNum(firstName,errorFirstName,"First name can't be numbers!");
boolean isLastNameEmpty = validate.emptyError(lastName,errorLastName,"Last name is required!");
boolean isLastNameNum = validate.isNotNum(lastName,errorLastName,"Last name can't be numbers!");
boolean isEmailEmpty = validate.emptyError(email,errorEmail,"Email address is required!");
boolean isPasswordEmpty = validate.emptyError(password,errorPassword,"Password is required!");
boolean isemailValid = validate.isValidEmailAddress(email);
boolean isPasswordValid = validate.isValidPassword(password,confirmPassword,errorPassword);
boolean isPasswordMatched = validate.isPasswordMatch(password,confirmPassword);
boolean isUserNameExist = validate.checkUsernameExists(email.getText(),connec,errorEmail);
if(isFirstNameEmpty && isFirstNameNum && isLastNameEmpty && isLastNameNum && isEmailEmpty && isPasswordEmpty && isPasswordValid && isemailValid && isPasswordMatched && isUserNameExist){
PreparedStatement pstmt = null;
String sql = "UPDATE users\n" +
"SET firstName = ?, lastName= ?, email= ?, mobile= ?, occupation= ?, address= ?, password= ?, notes= ?\n" +
"WHERE email = ?;";
try {
pstmt = connec.prepareStatement(sql);
pstmt.setString(1,firstName.getText());
pstmt.setString(2,lastName.getText());
pstmt.setString(3,email.getText());
pstmt.setString(4,mobile.getText());
pstmt.setString(5,occupation.getText());
pstmt.setString(6,address.getText());
pstmt.setString(7,password.getText());
pstmt.setString(8,notes.getText());
pstmt.setString(9,mail);
int i = pstmt.executeUpdate();
System.out.println("customer info UPDATE status = " + i);
if(i == 1){
AlertBox.displayAlertBox("Congratulations!","You have successfully registered to JFS");
sceneSwitcher.switchScene(updateButton,"sample.fxml","JFS");
}else{
AlertBox.displayAlertBox("Error","Database couldn't be updated");
}
} catch (SQLException e) {
System.err.println(e);
}finally {
pstmt.close();
}
AlertBox.displayAlertBox("Congratulations!","You have successfully updated your account");
sceneSwitcher.switchScene(updateButton,"sample.fxml","JFS");
}else{
System.out.println("Validation failed");
}
}
public void backButtonClicked(ActionEvent actionEvent) {
sceneSwitcher.switchScene(backButton,"customerView.fxml","Welcome to JFS ");
}
}
我想获得用户在登录屏幕中输入的电子邮件,以便在此控制器中使用。因为我需要那封邮件来确认用户的身份。但它显示为空。请帮我找出问题所在。
最佳答案
发生此问题的原因是,在试图向其传递值的ViewMyActivity控制器中调用Initialize之前,您没有在代码中设置邮件变量。
获取下面的代码并创建一个项目并测试它。这展示了如何在一个简单但主要是功能性的javafx fxml布局中在控制器之间传递值。
第一次登录布局.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<GridPane fx:controller="FXMLController"
xmlns:fx="http://javafx.com/fxml"
alignment="center"
hgap="10"
vgap="10"
styleClass="root">
<Text id="welcome-text" text="Login Below:"
GridPane.columnIndex="0" GridPane.rowIndex="0"
GridPane.columnSpan="2"/>
<padding><Insets top="25" right="25" bottom="10" left="25" /></padding>
<Label text="Username:" GridPane.columnIndex="0" GridPane.rowIndex="1" />
<TextField fx:id="usernameField" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<Label text="Password:" GridPane.columnIndex="0" GridPane.rowIndex="2" />
<PasswordField fx:id="passwordField" GridPane.columnIndex="1" GridPane.rowIndex="2" />
<HBox spacing="10" alignment="bottom_right"
GridPane.columnIndex="1" GridPane.rowIndex="4">
<Button text="Login"
onAction="#handleLogin" />
</HBox>
<Text fx:id="usernameEntered" GridPane.columnIndex="1" GridPane.rowIndex="6" />
</GridPane>
现在,fxmlcontroller:
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
public class FXMLController {
ViewMyAccount viewMyAccount = new ViewMyAccount();
@FXML private Text usernameEntered;
@FXML private TextField usernameField;
@FXML protected void handleLogin(ActionEvent event) {
String enteredValue = usernameField.getText().toString();
usernameEntered.setText("Username: " + enteredValue);
System.out.println("From Controller: " + enteredValue);
System.out.println("From ViewMyAccount: "+
viewMyAccount.setAndReturnMail(enteredValue));
//I cannot tell why you want to call initialize from
//ViewMyAccount, but this is a test showing it works
viewMyAccount.initialize(null, null);
}
}
现在fxmlmain,运行这个类:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FXMLMain extends Application {
public static void main(String[] args) {
//you should know this but this is how you launch your application
Application.launch(FXMLMain.class, args);
}
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("loginLayout.fxml"));
stage.setTitle("Login");
stage.setScene(new Scene(root, 600, 475));
stage.show();
}
}
现在你的viewMyAccount类,注意我注释掉了所有没有代码就无法运行的“片段”:
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.event.ActionEvent;
public class ViewMyAccount implements Initializable {
public Label errorPassword;
public Label errorMobile;
public Label errorEmail;
public Label errorLastName;
public Label errorFirstName;
public TextField notes;
public TextField address;
public PasswordField confirmPassword;
public PasswordField password;
public TextField occupation;
public TextField mobile;
public TextField email;
public TextField lastName;
public TextField firstName;
public Button updateButton;
public Button backButton;
//I don't have this code...
//Connectivity connection = new Connectivity();
//Connection connec = connection.getConnection();
//registerValidation validate = new registerValidation();
//SceneSwitcher sceneSwitcher = new SceneSwitcher();
public String mail = "mangalika@gmail.com"; //I want the logged in mail to assign this
public String setAndReturnMail(String userEnteredValue) {
this.mail = userEnteredValue;
return this.mail;
}
public void initialize(URL url, ResourceBundle rb) {
//fill info in fields
PreparedStatement pstmtGetInfo = null;
ResultSet rslt = null;
String sqlGetInfo = "SELECT * FROM users WHERE email=?";
System.out.println(mail);
/*
try {
pstmtGetInfo = connec.prepareStatement(sqlGetInfo);
pstmtGetInfo.setString(1,mail);
rslt = pstmtGetInfo.executeQuery();
if(rslt.next()){
StringBuffer stringBuffer1 = new StringBuffer();
stringBuffer1.append(rslt.getString("firstName"));
firstName.setText(stringBuffer1.toString());
StringBuffer stringBuffer2 = new StringBuffer();
stringBuffer2.append(rslt.getString("lastName"));
lastName.setText(stringBuffer2.toString());
StringBuffer stringBuffer3 = new StringBuffer();
stringBuffer3.append(rslt.getString("email"));
email.setText(stringBuffer3.toString());
StringBuffer stringBuffer4 = new StringBuffer();
stringBuffer4.append(rslt.getString("mobile"));
mobile.setText(stringBuffer4.toString());
StringBuffer stringBuffer5 = new StringBuffer();
stringBuffer5.append(rslt.getString("occupation"));
occupation.setText(stringBuffer5.toString());
StringBuffer stringBuffer6 = new StringBuffer();
stringBuffer6.append(rslt.getString("address"));
address.setText(stringBuffer6.toString());
StringBuffer stringBuffer7 = new StringBuffer();
stringBuffer7.append(rslt.getString("password"));
password.setText(stringBuffer7.toString());
confirmPassword.setText(stringBuffer7.toString());
StringBuffer stringBuffer8 = new StringBuffer();
stringBuffer8.append(rslt.getString("notes"));
notes.setText(stringBuffer8.toString());
}else{
System.out.println("no rows for this mail ID");
}
} catch (SQLException e) {
System.err.println(e);
}
*/
}
public void updateButtonClicked(ActionEvent actionEvent) throws SQLException{
/* boolean isFirstNameEmpty = validate.emptyError(firstName,errorFirstName,"First name is required!");
boolean isFirstNameNum = validate.isNotNum(firstName,errorFirstName,"First name can't be numbers!");
boolean isLastNameEmpty = validate.emptyError(lastName,errorLastName,"Last name is required!");
boolean isLastNameNum = validate.isNotNum(lastName,errorLastName,"Last name can't be numbers!");
boolean isEmailEmpty = validate.emptyError(email,errorEmail,"Email address is required!");
boolean isPasswordEmpty = validate.emptyError(password,errorPassword,"Password is required!");
boolean isemailValid = validate.isValidEmailAddress(email);
boolean isPasswordValid = validate.isValidPassword(password,confirmPassword,errorPassword);
boolean isPasswordMatched = validate.isPasswordMatch(password,confirmPassword);
boolean isUserNameExist = validate.checkUsernameExists(email.getText(),connec,errorEmail);
if(isFirstNameEmpty && isFirstNameNum && isLastNameEmpty && isLastNameNum && isEmailEmpty && isPasswordEmpty && isPasswordValid && isemailValid && isPasswordMatched && isUserNameExist){
PreparedStatement pstmt = null;
String sql = "UPDATE users\n" +
"SET firstName = ?, lastName= ?, email= ?, mobile= ?, occupation= ?, address= ?, password= ?, notes= ?\n" +
"WHERE email = ?;";
try {
pstmt = connec.prepareStatement(sql);
pstmt.setString(1,firstName.getText());
pstmt.setString(2,lastName.getText());
pstmt.setString(3,email.getText());
pstmt.setString(4,mobile.getText());
pstmt.setString(5,occupation.getText());
pstmt.setString(6,address.getText());
pstmt.setString(7,password.getText());
pstmt.setString(8,notes.getText());
pstmt.setString(9,mail);
int i = pstmt.executeUpdate();
System.out.println("customer info UPDATE status = " + i);
if(i == 1){
AlertBox.displayAlertBox("Congratulations!","You have successfully registered to JFS");
sceneSwitcher.switchScene(updateButton,"sample.fxml","JFS");
}else{
AlertBox.displayAlertBox("Error","Database couldn't be updated");
}
} catch (SQLException e) {
System.err.println(e);
}finally {
pstmt.close();
}
AlertBox.displayAlertBox("Congratulations!","You have successfully updated your account");
sceneSwitcher.switchScene(updateButton,"sample.fxml","JFS");
}else{
System.out.println("Validation failed");
}
*/
}
public void backButtonClicked(ActionEvent actionEvent) {
// sceneSwitcher.switchScene(backButton,"customerView.fxml","Welcome to JFS ");
}
}