Search code examples
javafor-loopjtextfielduser-inputgetter

Java getText of looped multiple JTextFields


My first question here. Already got a lot of help but now I don't know how to do.

My code:

package view;

import javax.swing.*;

public class OptionPlayerNames {

JPanel playerPanel = new JPanel();
JTextField playerNames = new JTextField();

public OptionPlayerNames() {
    for (int i = 0; i < 8; i++) {

// JTextField playerNames = new JTextField();

playerPanel.add(new JLabel("Player " + (i + 1))); playerPanel.add(playerNames); } playerPanel.setLayout(new BoxLayout(playerPanel, BoxLayout.Y_AXIS)); playerPanel.add(Box.createHorizontalStrut(5)); } public JPanel getPanel(){ return playerPanel; } public String getPlayerNames() { return playerNames.getText(); }

I want to have 8 Jlabels with just under it 8 JTextFields for user input. Then get the text of the textfields. Now I get only 1 text from 1 textField. Off course I only add 1 field.

When I put the JTextField under the for loop I get what I want but how to I get the text from all the JTextFields then? playerNames is then not known in the getter.

Thank you for your help.


Solution

  • You can do as follows, creating a Listof JTextField:

    JPanel playerPanel = new JPanel();
    List<JTextField> playerNames = new ArrayList<JTextField>();
    
    public OptionPlayerNames() {
        for (int i = 0; i < 8; i++) {
            JTextField playerName = new JTextField();
    
            playerPanel.add(new JLabel("Player " + (i + 1)));
            playerPanel.add(playerName);
    
            playerNames.add(playerName);
        }
        playerPanel.setLayout(new BoxLayout(playerPanel, BoxLayout.Y_AXIS));
        playerPanel.add(Box.createHorizontalStrut(5));
    }
    
    public JPanel getPanel() {
        return playerPanel;
    }
    
    public String getPlayerNames() {
        String output = "";
        // Compound you exit from the playerNames List
        // Or better, return a List of String
        return output;
    }