Search code examples
javaswingjlabeljtextfield

Editing JLabel from JTextField in another class


I've looked around but nothing seems to help me out. Basically I'm writing a multithreaded chat program with a gui. The user inputs his name in a textfield in a Login class and hits the login button which directs him to a ClientGUI class. In the client GUI class theres a JLabel at the top that says

"Welcome to the ChatSystem (Username)"

. So what the user input in the textfield in the login class should appear in the JLabel after "Welcome to the ChatSystem" but I can't figure out why it doesn't work. Here's my code:

Login Class:

loginB = new JButton("Login");
main.add(loginB);
loginB.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        ClientGUI clientgui = new ClientGUI();
        clientgui.setVisible(true);
    }
}

ClientGUI class:

public ClientGUI(){
    Login login = new Login();
    String username = login.usernameTF.getText();
    welcome = new JLabel("Welcome to ChatSystem "+username, SwingConstants.CENTER);

}

I understand that username should really by a JLabel and not a String but I have tried many ways to do this and I can't seem to get my head around this.


Solution

  • That is not going to work like that because login.usernameTF.getText(); is actually a new created object in the ClientGUI constructor...

    what I would suggest to do is to overload the constructor and to pass the name as parameter...

    Example:

     loginB.addActionListener(new ActionListener(){
         @Override
         public void actionPerformed(ActionEvent e) {
         ClientGUI clientgui = new ClientGUI(getTheNameAndpassItHere);
         clientgui.setVisible(true);
                }
            }
    

    and then ClientGUI class:

    public ClientGUI(String username){
    
        //Login login = new Login();
       // String username = login.usernameTF.getText();
    
        welcome = new JLabel("Welcome to ChatSystem "+username, SwingConstants.CENTER);
    
    }