Jollyfreak Jollyfreak - 7 months ago 59
Java Question

Passing string and variable from one class to another. JAVA

I coded Chat in java with gui. Now I made a simple Login with MySQL. If you login you open main chat class. But problem is I want to pass username string from login class to main class.
How to do it. And how to pass variable from one to another class too. thx guys

CODE:

Here is where you login and it opens new class

Login class. login2.java

if (res.next()) {
JOptionPane.showMessageDialog(this, "Login Sucessfull.");
new ClientGUI("localhost", 1500);
dispose();
}
else {
JOptionPane.showMessageDialog(this, "Invalid User Name/Passw");
}


Thank you for help.

Answer

Here is what I would do...create a public variable or a public object like:

public static String keepInfo; // on top of your code

Instantiate it in your code by giving it whatever value you want in the constructor. Then the class that wants to call should create an object of the class. In your case, it would something like:

ClientGUI client = new ClientGUI();
// to call your String you can do something like:
String getInfo = client.keepInfo; // if you don't have get or set methods
Comments