Instantiating array in a for loop to create JTextFields

爱⌒轻易说出口 提交于 2019-12-11 13:12:12

问题


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.


 }

回答1:


It's unclear is FIELDS is your JTextField aray 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.




回答2:


This might help.

Container c = getContentPane();

c.setLayout(new FlowLayout());
JTextField[] txt = new JTextField[FIELDS]; // FIELDS is an int, representing the max number of JTextFields

 int i = 0;
 for (i = 0; i < FIELDS; i++)
 {
   txt[i] = new JTextField();
   // add any listener you want to txt[i]
   c.add(txt[i]);
 }


来源:https://stackoverflow.com/questions/16195134/instantiating-array-in-a-for-loop-to-create-jtextfields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!