0

I got thow panels. The first one contains a JTextField in order to get the username of the player


public class FirstPanel extends JPanel {
   public static final JTextField usernameText = new JTextField(30);
   public FirstPanel() {

       this.setBackground(Color.GREEN);
       JLabel enterName = new JLabel("ENTER YOUR NAME");
       this.add(enterName);
       this.add(usernameText);
       usernameText.addActionListener(e ->
       {
           if (isThereUsername()) ;
          CardLAyout.cl.show(CardLAyout.panelCont, "2");
       });

when you enter a text you are redirected to another panel where I would like to display the following message "Hello *username obtained from the first panel thanks to the JTextfield" let's play a game.

I wrote the following code in the class of my second JPanel (the ifThereUsername function is just used to say if there was text or not). However the user name is not displayed I just read the rest of the message

if (FirstPanel.isThereUsername()) {
                hello = new JLabel("HELLO " + FirstPanel.getUsername() + "\n LET'S START THE GAME RIGHT NOW ! ");
                this.add(hello);
            } else {
                hello = new JLabel("HELLO \n let's start the game !");
                this.add(hello);
            }

the fonction getUsername is in the first panel

 public static String getUsername(){
        return usernameText.getText();
        }

I really struggle to connect the classes between them at first I wrote all my JPanel in the same class but it's very messy. So I use static methods

  • 1
    You can add the `hello` label when you create the panel. Just give it no text. Then when you want to change the text, call method `setText`. Your problem is that you are adding components after the GUI has been displayed. If you want better help, then post a [mcve]. – Abra Jan 24 '22 at 16:09
  • 1. The request to post mre repeats with every question you asked: [1](https://stackoverflow.com/questions/70219312/got-on-error-javax-imageio-iioexception-cant-read-input-file-when-i-tried) [2](https://stackoverflow.com/questions/70229919/how-to-add-a-panel-created-in-another-class-to-a-jframe) [3](https://stackoverflow.com/questions/70825068/i-have-a-problem-with-inteliji-idea-my-classes-are-not-recognized-as-classes-by). – c0der Jan 25 '22 at 05:49

1 Answers1

0

static access is not recommended...

Give the FirstPanel access to the SecondPanel (or the other way around)

in FirstPanel introduce the needed constructor and remember the reference to the secondPanel in a field

and in addActionListener implmentation call secondPanel.setUserName();

public FirstPanel() {
    private SecondPanel secondPanel;
    FirstPanel(SecondPanel secondPanel) {
       secondPanel = secondPanel;
    }

}

somewhere in your code: new FirstPanel(secondPanel);

Jvo
  • 46
  • 4