1

我需要使用 forloop 和 text_fields 实例变量来实例化每个文本字段,使其成为侦听器,并将其添加到小程序中。text_fields 变量是一个数组,其最大数组数为 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.


 }
4

2 回答 2

1

这可能会有所帮助。

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]);
 }
于 2013-04-24T15:02:31.757 回答
0

目前还不清楚是FIELDS你的JTextFieldaray 还是常数。如果是组件数组本身,.length在迭代时考虑使用数组字段。这减少了代码维护:

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]);
}

请注意,大写变量用于 Java 命名约定下的常量。

于 2013-04-24T15:03:30.237 回答