如何在java中将变量从一个Jframe(或类)传递到另一个?

时间:2015-05-13 18:12:12

标签: java swing netbeans return-value encapsulation

我已经看过几个可以返回值的示例,但我并不完全理解如何使它们在我自己的代码中工作。我想我应该在这里发布,看看我是否能得到一些好的指针。我需要检查用户是否已登录,然后如果他们已登录打开窗口以允许他们创建事件(我可以使用if,then和else语句使逻辑工作)。我需要帮助的部分是将变量从登录类传递给CreateEventActionPerformed。以下内容来自我的mainFrame Jframe类:

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:
    } 

以下内容来自登录jframe类:

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



    }

我还没有发布我的所有代码,我希望这足以帮助我解决这个问题。我已经考虑过getter和/或setter方法,但我不知道如何做到这一点。

1 个答案:

答案 0 :(得分:1)

假设您必须使用getter / setter,这是正确的。因此,首先在登录JFrame类的顶部添加一个getter方法和一个布尔值。

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
}

然后只需将isLoggedIn变量设置为您想要的true

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();
    ....
}

最后,在CreateEventActionPerformed方法中,您需要创建或重用JFrame登录类的当前实例,并使用它来调用getIsLoggedIn()方法。

例如,如果要创建登录类的新实例,只需将此位添加到CreateEventActionPerformed方法中,其中LoginClass是登录类的名称。

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

然后,您可以使用布尔值执行您喜欢的任何检查或活动。同样的过程(创建一个getter方法)也可用于跨类传递un变量。

请注意,如果您想将变量保存到内存中(这样可以在应用程序关闭时保留它们),您将需要查看storing persistent data.

祝您好运,如果您有任何疑问,请告诉我们!