私はJavaFXの中に別のシーンに値を渡すしようとすると、セッターメソッドが動作しません

Thdbhoy:

私はJavaで複数のシーン間のセッターメソッドを介して値を渡すためにしようとしています。しかし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 = "[email protected]"; //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 ");
        }




    }

私はこのコントローラで使用するログイン画面でユーザが入力した電子メールを取得したいです。私は、プロセスを介してユーザーを識別するために、その電子メールを必要とするので。それはNULLとして表示されます。間違っているのかを見つけるために私を助けてください。

ViaTech:

あなたが設定されていないので、あなたの問題が発生しているメール初期化がで呼び出される前に、あなたのコード内の変数をViewMyActivityのあなたに値を渡すためにしようとしているコントローラ。

以下の私のコードを取り、プロジェクトを作成し、それをテスト。これは単純に、コントローラ間で値を渡す方法を示しますが、ほとんどの機能のJavaFX FXMLレイアウト。

まず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 = "[email protected]"; //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 ");
        }

}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=221366&siteId=1