Search code examples
javaarraysappletjtextfield

Instantiating array in a for loop to create JTextFields


I need to use a forloop and the text_fields instance variable to instantiate each text field, make it a listener, and add it to the applet. The text_fields variable is an array which has a max number of arrays of 2.

Container c = getContentPane();

c.setLayout(new FlowLayout());


 int i = 0;
 for (i = 0; i < FIELDS; i++)
 {
   THIS IS WHERE I DON'T KNOW WHAT TO WRITE.
       i need to instantiate the arrays, make them listeners and 
       add them to the applet.


 }

Solution

  • It's unclear if FIELDS is your JTextField array or a constant. If it is the component array itself, consider using the .length array field when iterating. This reduces code maintenance:

    JTextField[] fields = new JTextField[SIZE];
    for (int i = 0; i < fields.length; i++) {
       fields[i] = new JTextField("Field " + i);
       fields[i].addActionListener(myActionListener);
       c.add(fields[i]);
    }
    

    Note uppercase variables are used for constants under Java naming conventions.