nanoo
nanoo

Reputation: 185

Getting content from JTextFields created dynamically

I am learning Java with Swing and I have some problems with using JTextField. In my program I want to dynamically add a few JTextFields with some text:

while( (ln = bufFile.readLine()) != null ) {
    // inIdPanel is JPanel
    inIdPanel.add(new JTextField(ln));
}

And it works good. However, the content of these JTextFields can be modified by users, and later I want to call getText() from all of them. Is this possible? How can I do this?

I saw this question: Java Swing: JButton creates new JTextField(s) but this isn't enough to solve my problem (I think using arrays in my case is not a good idea but maybe I'm wrong).

Upvotes: 1

Views: 1691

Answers (2)

n00begon
n00begon

Reputation: 3492

The reason why you cannot call getText() is that you have not stored a reference to the JTextField when you created it. You will need to use an array or collection to store the JtextFields as you create them so you can call the method on them later. A collection will be easier than an array because you do not know how many lines you will read in so you want it to be able to grow.

List<JTextField> fields = new ArrayList<JTTextField>();
while( (ln = bufFile.readLine()) != null ) {
    JTextField field = new JTextField(ln);
    inIdPanel.add(field);
    fields.add(field);
}

Then you can call the .getText() from all of them

for(JTextField field: fields){
    System.out.println(field.getText());
}

Upvotes: 2

Michael
Michael

Reputation: 1239

For an easy solution, just add an ArrayList<JTextField> textFieldList and add to the code you posted:

while((ln = bufFile.readLine()) != null) {
    textFieldList.add(new JTextField(ln));
    inIdPanel.add(textFieldList.get(textFieldList.size()-1));
}

Then, when you want to access the text fields, you simply iterate through them, e.g.

for (JTextField jtf : textFieldList) {
    /* Operate on jtf, call methods, etc */
}

You could replace the ArrayList with an array if there is a defined limit on how many text fields you could add, but the list is nice if that quantity is unknown.

Upvotes: 2

Related Questions