Search code examples
javaswingiojtextfield

get ordered value of jtextfield


With the help of Oliver Schmidt I could get text from dynamically added jTextFields.

Now I have jPanel1 with jTextField1 generated by Netbeans:

jTextField1 = new javax.swing.JTextField();
jPanel1.add(jTextField1);
jPanel1.setLayout(new org.jdesktop.swingx.VerticalLayout());

Also by AddButton adding dynamic jTextFields to jPanel1:

jPanel1.add(new subPanel());
pack();

The problem I get stuck is when I push the SaveButton I am getting not ordered output text.

for (Component spChild : spChildren) {
       if (spChild instanceof JTextField) {
             String text = ((JTextField)spChild).getText();
             System.out.println(jTextField1.getText()); //I think this code is wrong
             System.out.println(text);

For example, if the value of:

jTextField1: 1,

Dynamic JTextFields: 2, 3.

Output I am getting repeated jTextField1:

1

2

1

3

Desired output is:

1

2

3

I don't know how to avoid this problem.


Solution

  • You are correct, you need to remove jTextField1 from your loop and just print it above the loop and then loop through the dynamic text boxes.

    // Move jTextField1 to print before your print the dynamic JTextBoxes
    System.out.println(jTextField1.getText()); 
    for (Component spChild : spChildren) {
           if (spChild instanceof JTextField) {
                 String text = ((JTextField)spChild).getText();
                 System.out.println(text);