Search code examples
javaarraysswingfor-loopjtextfield

Accessing values of individual JTextFields created in a loop


Here is how I created the labels and JTextFields:

    JPanel panel3 = new JPanel(new SpringLayout());
    String[] labels = {"Non-animated image name:","Left animation image name:","Top animation image name:",
            "Right animation image name:","Bottom animation image name:"};
    for(int i=0; i<labels.length; i++){
        JLabel l = new JLabel(labels[i],JLabel.TRAILING);
        JTextField n = new JTextField(10);
        panel3.add(l);
        l.setLabelFor(n);
        panel3.add(n);
    }

    SpringUtilities.makeCompactGrid(panel3,
            5, 2,
            6, 6,
            6, 6);

Say for example, how would I access/get the value of the text in the JTextField with the label, "Top animation image name:"?

I know that usually, one can perform JTextField.getText(), but to me it looks like that wouldn't work here.

Thanks in advance!


Solution

  • This is just a specific example of the question:

    how can I access an object created in a loop.

    The answer is the same: put them in a collection or array. Note that the collection option has greater flexibility. For instance if you create a bunch of JLabel/JTextField associations, you could use a HashMap<String, JTextField> to associate the JTextField with a String.

    For example:

    Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
    String[] labels = {"Non-animated image name:","Left animation image name:","Top animation image name:",
            "Right animation image name:","Bottom animation image name:"};
    for(int i=0; i<labels.length; i++){
        JLabel l = new JLabel(labels[i],JLabel.TRAILING);
        JTextField n = new JTextField(10);
        panel3.add(l);
        l.setLabelFor(n);
        panel3.add(n);
        fieldMap.put(labels[i], n);
    }
    
    // and then later you can get the text field associated with the String:
    String text = fieldMap.get(labels[2]).getText();
    

    Or for a full example:

    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class InputForm extends JPanel {
       private static final int COLUMNS = 10;
       private static final int GAP = 3;
       private static final Insets LABEL_INSETS = new Insets(GAP, GAP, GAP, 15);
       private static final Insets TEXTFIELD_INSETS = new Insets(GAP, GAP, GAP, GAP);
       private String[] labelTexts;
       private Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
    
       public InputForm(String[] labelTexts) {
          this.labelTexts = labelTexts;
          setLayout(new GridBagLayout());
          for (int i = 0; i < labelTexts.length; i++) {
             String text = labelTexts[i];
             JTextField field = new JTextField(COLUMNS);
             fieldMap.put(text, field);
    
             addLabel(text, i);
             addTextField(field, i);
          }
       }
    
       public String[] getLabelTexts() {
          return labelTexts;
       }
    
       private void addTextField(JTextField field, int row) {
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.gridwidth = 1;
          gbc.gridheight = 1;
          gbc.gridx = 1;
          gbc.gridy = row;
          gbc.anchor = GridBagConstraints.EAST;
          gbc.fill = GridBagConstraints.HORIZONTAL;
          gbc.insets = TEXTFIELD_INSETS;
          gbc.weightx = 1.0;
          gbc.weighty = 1.0;
          add(field, gbc);
       }
    
       private void addLabel(String text, int row) {
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.gridwidth = 1;
          gbc.gridheight = 1;
          gbc.gridx = 0;
          gbc.gridy = row;
          gbc.anchor = GridBagConstraints.WEST;
          gbc.fill = GridBagConstraints.BOTH;
          gbc.insets = LABEL_INSETS;
          gbc.weightx = 1.0;
          gbc.weighty = 1.0;
          add(new JLabel(text), gbc);
       }
    
       public String getFieldText(String key) {
          String text = "";
          JTextField field = fieldMap.get(key);
          if (field != null) {
             text = field.getText();
          }
          return text;
       }
    
       private static void createAndShowGui() {
          String[] labelTexts = new String[] { "One", "Two",
                "Three", "Four" };
          InputForm inputForm = new InputForm(labelTexts);
    
          int result = JOptionPane.showConfirmDialog(null, inputForm, "Enter Stuff Here",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
          if (result == JOptionPane.OK_OPTION) {
             for (String text : labelTexts) {
                System.out.printf("%20s %s%n", text, inputForm.getFieldText(text));
             }
          }
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }