Jollyfreak Jollyfreak - 2 years ago 176
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


Here is where you login and it opens new class

Login class.

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

Thank you for help.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download