Search code examples
javaswingnetbeansreturn-valueencapsulation

How do I pass variables from one Jframe (or class) to another in java?


I have looked at a couple of examples that would return values, but I don't fully understand how to make them work in my own code. I figured I should post it here and see if I can get some good pointers. I need to do a check to see if the user has logged in, then if they have logged in open the window to allow them to create the event(I can make the logic work with the if, then, and else statements). The part I need help with is passing the variables from the login class to the CreateEventActionPerformed . The following is from my mainFrame Jframe class:

private void CreateEventActionPerformed(java.awt.event.ActionEvent evt) {                                            
//This is where I want to check for the login variable to allow or deny the user access
//if the have logged in then new CreateEvent().setVisible(true);
//if the user has not yet logged in, then open the the login window.
        // note the only piece that I need help with is getting the varible from the CdEventPlannerLogin()  jframe.
        // the varrible will be from the submit button also put as SubmitActionPerformed(java.awt.event.ActionEvent evt) I think
       new CdEventPlannerLogin().setVisible(true);

// Once the user has logged in then new CreateEvent().setVisible(true); 
//I also need to maintain the username (variable is un) from the  CdEventPlannerLogin()
//I need it for the next page. 
        //new CreateEvent().setVisible(true);
        // TODO add your handling code here:
    } 

The Following is from The login jframe class:

private void SubmitActionPerformed(java.awt.event.ActionEvent evt) {                                       
        String un = UserName.getText().trim();
        String pw = Password.getText().trim();
        HashSet hs= new HashSet();
        HashSet users = new HashSet(); 
        boolean goahead=true;

    try {
            Scanner Scan = new Scanner(new File("Login.txt"));
    while (Scan.hasNextLine()) 
            { 
            String authenticator = Scan.nextLine().trim();
            String[] autparts=authenticator.split(" "); 
            String user = autparts[0];
            if (goahead)
                {
               if (users.contains(user)) 
                    {
               if (user.equals(un))
//this checks for a duplicate user when loging in, and denies access if a duplicate is found
                        {    
            JOptionPane.showMessageDialog(null, "Duplicate user found. Access Denied"); 
            goahead=false;
            dispose();
                        }
                    } else {
                hs.add(authenticator);
                users.add(user);
                           }
                }
            }

            } catch (Exception ex) { 
            ex.printStackTrace(); 
                                   } 
        if (goahead) {
//if the user has checked the box it will prevent the user from creating an account if one already exsist
            if (createAccount.isSelected() & (hs.contains(new String(un+" "+pw))))                             
            {
            JOptionPane.showMessageDialog(null,"Account Already Exsist! No Need to create a new account. Please try again.");
            dispose();

            } else { if (hs.contains(new String(un+" "+pw))) 
                        { 
                JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
//this is where I need a varriable or boolean of some kind granting access to other portion of the program.
//I need this value to be accessed by other classes to grant that access. 
                dispose();
                        } else { 
            if (createAccount.isSelected())
//if the user has selected the create account box 
//it will allow him to make one base on the values entered
               {
               try {
        PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("Login.txt", true)));
        output.close(); 
                   } catch (IOException ex) {
                                            System.out.printf("error %s/n", ex );
                                            } 
//below sends a message to the user that their account has been created. 
                JOptionPane.showMessageDialog(null,"Welcome!"+" " + un+" "+"Your account is now created. You may now login");
                dispose();
               }else {
                        JOptionPane.showMessageDialog(null, "user doesn't exist or password incorrect. "); 
                        dispose();
                      }
                              }
                   }
                      }



    }

I haven't posted all of my code I hope this is enough to help me figure this out. I have thought about getter and or setter methods, but I am not sure how to make that work either.


Solution

  • You are correct in the assumption that you have to use getters/setters. So, first off add a getter method and a boolean at the top of your login JFrame class.

    public class mainFrame {
        ....
        boolean isLoggedIn = false; // By default their not logged in
    
        // Getter method to get value of the boolean
        public boolean getIsLoggedIn() {
            return isLoggedIn;
        }
        ... Rest of code not shown
    }
    

    Then simply set the isLoggedIn variable to true where you want it to be:

    private void SubmitActionPerformed(java.awt.event.ActionEvent evt) {
    
        ... Other code not shown
    
        //this is where I need a varriable or boolean of some kind granting  access 
        // to other portion of program
        // I need this value to be accessed by other classes to grant that access. 
        isLoggedIn = true;
        dispose();
        ....
    }
    

    Finally, in the CreateEventActionPerformed method you need to create or reuse the current instance of the JFrame login class and use that to invoke the getIsLoggedIn() method.

    For example, if you wanted to create a new instance of the login class simply add this bit to your CreateEventActionPerformed method, where LoginClass is the name of your login class.

    LoginClass login = new LoginClass();
    boolean isLoggedIn = login.getIsLoggedIn();
    

    You can then use the boolean to perform whatever checks or activities you like. This same process (of creating a getter method) can also be used to pass the un variable across classes.

    Please note that if you want to save the variables into memory (so they can be preserved across application shutdowns) you will have to look into storing persistent data.

    Best of luck, if you have any questions please let me know!