Dennis Martinez
Dennis Martinez

Reputation: 6512

Is there a way to loop through dynamically created componenets in java?

I am dynamically creating jtextfields and I was wondering if there was a way to loop through each one and check for it's value

something like this:

foreach(JTextField:jtf in JFrame)
    System.out.prinlnt(jtf.getText());

Edit:

The current way I'm doing this is creating an array list:

private ArrayList<JTextField> txtFields = new ArrayList<JTextField>();

When I call createDynamic:

final JTextField txtDirPath = new JTextField(20);
txtFields.add(txtDirPath);

Then on my button I have an action which perform this:

for (int i = 0; i < txtFields.size(); i++) {
    String strPath = txtFields.get(i).getText();
    System.out.println(txtFields.size());
    System.out.println(strPath);
}

Upvotes: 0

Views: 1201

Answers (4)

wil
wil

Reputation: 11

for (Component c : jframe.getComponents()) {
    if (c instanceof JTextField)
        System.out.println(((JTextField)c).getText());
}

Upvotes: 1

John B
John B

Reputation: 32949

for(Component c : myJFrame.getComponents){
   if (c instanceof JTextField){
      // do work here
   }
}

Upvotes: 0

MByD
MByD

Reputation: 137282

If you don't want to store thos in a list as @JB Nizet proposed, You can call Container#getComponents to get an array of all the child components. And for each one check if it a JTextField.

Component[] compArr = myFrame.getComponents();
for (Component comp : compArr) {
    if (comp instanceof JTextField) {
        System.out.prinlnt(((JTextField)comp).getText());
    }
}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691655

Just put you text fields in a list (java.util.List<JTextField>) when creating them dynamically, and loop over this list :

for (JTextField jtf : theListOfTextFields) {
    System.out.prinln(jtf.getText());
}

Upvotes: 1

Related Questions