CSjunkie
CSjunkie

Reputation: 555

Java Swing - Dynamically create JTextField

I want to create several JTextFields that I can then get the user data from once they hit a submit button. I am using the code below to dynamically create labels for the text fields and was planning on creating the text fields in a similar way, but I realized that if I do that the fields won't have variable names and I won't be able to extract the data. Is there a way to dynamically assign variable names or otherwise retrieve the data from the text fields if I create them in a way similar to what's shown below?

    int autoX = 0;
    int autoY = 0;
    for (int i = 0; i< units.numOfUnits(); i++ ){
        c.gridx = (autoX % 5);
        c.gridy = autoY;
        if((autoX % 5) == 4){
            autoY++;
        }
        mainPanel.add(new JLabel(units.getUnit(i)),c);
        autoX++;
    }

Upvotes: 0

Views: 1891

Answers (1)

Samuel
Samuel

Reputation: 17171

You need to keep a reference to the text fields you create. Like this:

List<JTextField> textFields = new ArrayList<JTextField>();
int autoX = 0;
int autoY = 0;
for (int i = 0; i< units.numOfUnits(); i++ ){
    c.gridx = (autoX % 5);
    c.gridy = autoY;
    if((autoX % 5) == 4){
        autoY++;
    }
    mainPanel.add(new JLabel(units.getUnit(i)),c);
    JTextField textField = new JTextField();
    mainPanel.add(textField);
    textFields.add(textField);
    autoX++;
}

Then you can refer to a specific text field with:

textFields.get(0).getText();

Upvotes: 4

Related Questions