简体   繁体   中英

How to call a String or any datatype from another class in java

I have a LoginGUI and a MainGUI, what I want to do is return the current user as a String or the UserID as an Integer in my MainGUI. My program runs the LoginGUI and then if the UserName a password match up with the database it lets you through to the MainGUI. I've declared a CurrUserID and CurrUser in my LoginGUI - both are public, but how can I use them in my MainGUI?

Here is the code for my LoginGUI - I'm using swing.

    private void loginButActionPerformed(java.awt.event.ActionEvent evt) {                                         
    for (int i = 0; i <= size; i++) {
        if (login.getText().equals(users[i].getUser())) {
            currUser = users[i].getUserID();
            if (password.getText().equals(users[i].getPassword())) {
                try {
                    MainGUI main = new MainGUI(users);
                    main.setVisible(true);
                    this.dispose();
                } catch (SQLException ex) {
                    Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            else{
                JOptionPane.showMessageDialog(null, "Incorrect Password");
            }
        }
        else{
            JOptionPane.showMessageDialog(null, "Incorrect UserName");
        }
    }
}                                        

public int getCurrUser() {
    return currUser;
}

What I want to do is return the currUser while I'm in my MainGUI. How can I?

Add a member, say String uid; to your MainGUI class, and create two constructors, one that accepts String and other that accepts Integer ; in 'em, set uuid to whatever is passed. Now you'll have your user id tied to MainGUI for later use.

So, when you're done with LoginGUI, initialize the new MainGUI(passedID) .

You could add a setter method in your MainGUI class and call it like so:

main.setCurrentUser(currUser);

For passing multiple fields from LoginGUI to MainGUI you could use a wrapper class, eg

CurrUserDetails details = new CurrUserDetails(userID, userName);
main.setCurrentUserDetails(currUser);

in order to invoke any non-static method of a class, you require an instance of the class, for instance

public class Foo{
    public void bar(){
        // do stuff
    }
}

Foo f = new Foo();
f.bar(); // invoking non-static method of class Foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM