Search code examples
javauser-interfacejlabeljtextfield

How to display a textfield's text from a class into another class' label


I need help in how to get a textfield's text from a class and display it into a label which is from another class.

I just show the 2 classes, it is more easier to see/read what I'm trying to ask.

GameView.java

public void logIn()
    {
       loginFrame = new JFrame("FIshing Pair Game");
       loginFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
       loginFrame.setResizable(true);

       gridBag = new GridBagLayout();

       loginPanel = new JPanel();
       loginPanel.setBackground(Color.LIGHT_GRAY);
       loginPanel.setPreferredSize(new Dimension(400,400));
       loginPanel.setLayout(gridBag);

       loginTitleLbl = new JLabel("Login to Play!");
       loginTitleLbl.setFont(new Font("Britannic Bold",Font.PLAIN,22));

       nameLbl = new JLabel("Login name:");
       nameLbl.setFont(new Font("Agency FB",Font.BOLD,20));

       passLbl = new JLabel("Password:");
       passLbl.setFont(new Font("Agency FB",Font.BOLD,20));

       nameTxt = new JTextField();
       nameTxt.setPreferredSize(new Dimension(200,30));

       passTxt = new JPasswordField();
       passTxt.setPreferredSize(new Dimension(200,30));
       passTxt.setEchoChar('*');

       private class LoginBtnListener implements ActionListener
{
   public void actionPerformed(ActionEvent ae)
   {
       ArrayList<Player>players = new ArrayList<>();
       Scanner playerScan = null;

        try{
            playerScan = new Scanner(new File("players.dat"));
            while(playerScan.hasNextLine())
            {
                String playerData = playerScan.nextLine();
                String[] dataSplit = playerData.split("\\|");
                Player existingPlayer = new Player(dataSplit[0],dataSplit[1],dataSplit[2],Integer.parseInt(dataSplit[3]));
                players.add(existingPlayer);
            }
        }catch(FileNotFoundException ex){
            System.out.println("Error! File - players.dat not found!");
        }
        playerScan.close();

        boolean exist = false;

        String name = nameTxt.getText();
        String passWord = passTxt.getText();

        for(int i = 0; i < players.size(); i++)
        {
            if(players.get(i).getLoginName().equalsIgnoreCase(name))
            {
                exist = true;
            }
        }

        if(exist == true)
        {
            nameTxt.setText("");
            passTxt.setText("");
            JOptionPane.showMessageDialog(null,"Welcome back " + name + "!");
            javax.swing.UIManager.put("OptionPane.messageFont", new FontUIResource(new Font("Verdana", Font.ITALIC, 20))); 
            ShuffleCardsFrame fishingFrame = new ShuffleCardsFrame();
            fishingFrame.run();
            loginFrame.setVisible(false);
        }

        if(exist == false)
        {
            JOptionPane.showMessageDialog(null,"Error! Player " + name + " doesn't exist! Please try again.");
            javax.swing.UIManager.put("JOptionPane.messageFont", new FontUIResource(new Font("Baskerville Old Face", Font.BOLD, 20))); 
        }
   }

}

I need to get the name from the nametxt TextField and display it into this label from FishingPairFrame.java.

The name in the textfield is based on from the text file and the ArrayList.

FishingPairFrame.java

playerLbl = new JLabel("");

playerLbl.setFont(new Font("Agency FB",Font.BOLD,20));

UPDATED CODES

FishingPairFrame

playerName = gameView.getPlayerName();
playerLbl = new JLabel(playerName+" Matching Pair: 0");
playerLbl.setFont(new Font("Agency FB",Font.BOLD,20));

GameView.java

public String getPlayerName()
{
   return playerName;
}

public void setPlayerName(String playerName)
{
   this.playerName = playerName;
}
//in private loginbtnlistener class
playerName = nameTxt.getText();

Solution

    1. Create a public method in GameView.java that returns a string:

      private String name;
      
      public String getName() {
          return name;
      }
      
    2. in GameView set the new variable "name" when the text field gets populated.

    You can just make this

        String name = nameTxt.getText(); 
    

    into this:

        name = nameTxt.getText(); )
    
    1. in FishingPairFrame.java, call:

      GameView gameView = new GameView();
      String name = gameView.getName();
      

    Or make the method static if you do not have an instance of the GameView class in FishingPairFrame.

    This technique is called encapsulation (where you make a private variable accessible with getters and setters. Read up on it, it's very useful.