0

What my program is suppose to do is when the user logs into the system, the username which they have entered should be stored in a second class. The reason for this is the username will be used to display at the top right corner of every JFrame which is opened.

So all I want to know is how do I store the username in a class (Named userLogin.java) which is in the background, so when the user opens for example inventory JFrame the username from the userlogin will be displayed in a textbox, then if they proceed to for example salesList JFrame, the username will be called from the userlogin class and displayed in a textbox on this JFrame.

Here is my coding for userlogin.java

public class userlogin{
    //declare user strig for logged on user
    public String users;
    //default contructor
    public LoggedonUser()
    {

    }

   public void setUser(String loggeduser)
   {
       users = loggeduser;
   }
}

How do I alter this class in order to store and hold user input for calling from any JFrame throughout the system use.

Much appreciated for the help, to get this to work :)

Jay
  • 13
  • 1
  • 6
  • 4
    *"..every JFrame which is opened."* There should only ever be **one** frame created. 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) Instead use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Jul 27 '15 at 15:07
  • 2
    You could make `user` a static String and `setUser()` a static method, then when calling your JFrames you can get the name with `userLogin.users` – BoDidely Jul 27 '15 at 15:08
  • 1
    As already mentioned, you should use __CardLayout__, and simply provide a [TitledBorder](https://docs.oracle.com/javase/tutorial/uiswing/components/border.html#code) to the `JPanel` having a __CardLayout__ So simply speaking, just assign the username only once to the `TitledBorder` and it will remain as is, on all views :-) – nIcE cOw Jul 27 '15 at 15:10

2 Answers2

1

Hope this code help you;

In the login page add following method; note : usernametxt is the text field and It is public

public void showUsername(){
    String uname = usernametxt.getText();

}

In other Frames ;

note : username_lbl is the Label that get the user name

public void getUsername(String user){
    username_lbl.setText("Logged in as : "+user);
}
tenten
  • 1,276
  • 2
  • 26
  • 54
0

You can also use static variable for this

create a static variable

public static String USERNAME="";

and when you get username from user, you can,

USERNAME=txt_username.getText();

Then you can use in any class in the project as

userLogin.USERNAME;

NB:-clear the static value at the time of LOGOUT.

Anptk
  • 1,125
  • 2
  • 17
  • 28