1

I have an User Interface where the user inputs a number (10 for example) in a textfeild then if the user presses enter I want 10 text feilds to be generated in the same User Interface.

how can I do that?

0

4 Answers 4

2

Something like that:

// Assuming myOrigTextField is your original JTextField
int howMany = Integer.parseInt(myOrigTextField.getText());
JTextField[] jtfs = new JTextField[howMany];

for (int i = 0; i < jtfs.length; ++i) {
   jtfs[i] = new JTextField();
   myPanelToAddThem.add(jtfs[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Create the text field objects, add them to your container.

Use a loop to do this with an arbitrary number.

Post some code and your specific problems for more help.

Comments

1

Roughly assuming some thing about layout manager you're using I'd say this:

public List<JTextField> addComponents( int number ) {
    List<JTextField> fields = new ArrayList<JTextField>( number );
    for( int i = 0; i < number; i++ ) {
        fields.add( new JTextField() );
        panelToAddComponentsTo.add( fields.get( i ) );
    }
    return fields;
}

1 Comment

I'm not used to ArrayList yet and it's a shame... +1
1

if the user presses enter I want ? text feilds to be generated in the same User Interface

You add an ActionListener to the text field. The ActionListener will be invoked when the Enter key is pressed.

In the ActionListener code you need to parse the number entered and then loop to create and add the text fields to your panel:

for (...)
{
    panel.add( new JTextField(...) );
}

panel.revalidate(); // needed when dynamically adding/removing components
panel.repaint(); // sometimes needed

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.