gpt4 book ai didi

java - 当我尝试通过 javaFX 中的不同场景传递值时,Setter 方法不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:22:41 27 4
gpt4 key购买 nike

我正在尝试通过 setter 方法在 java 中的多个场景之间传递值。但是当我尝试这样做时,NullPointerException 弹出。我也想将电子邮件(用户名)保留在其他 Controller 中以识别用户。这是我的登录代码。

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");
}



}


}

这是我的登录界面:

Here is my login screen

我想将值传递给这个 Controller :

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 ");
}




}

我想获取用户在登录屏幕中输入的电子邮件,以便在此 Controller 中使用。因为我需要该电子邮件来通过流程识别用户。但它显示为空。请帮我找出问题所在。

最佳答案

出现问题是因为在尝试将值传递到的 ViewMyActivity Controller 中调用初始化之前,您没有在代码中设置 ma​​il 变量。

使用下面的代码创建一个项目并进行测试。这展示了如何在一个简单但主要是功能性的 JavaFX FXML 布局中的 Controller 之间传递值。

第一个loginLayout.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 ");
}

}

关于java - 当我尝试通过 javaFX 中的不同场景传递值时,Setter 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51565220/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com