【问题标题】:Instantiating array in a for loop to create JTextFields在 for 循环中实例化数组以创建 JTextFields
【发布时间】:2013-04-18 04:33:11
【问题描述】:

我需要使用 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.


 }

【问题讨论】:

  • 您已经尝试过的任何示例代码?

标签: java arrays applet jtextfield


【解决方案1】:

目前尚不清楚FIELDS 是您的JTextField 数组还是常量。如果是组件数组本身,迭代时考虑使用.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 命名约定下的常量。

【讨论】:

    【解决方案2】:

    这可能会有所帮助。

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

    【讨论】:

      猜你喜欢
      • 2018-04-02
      • 2018-04-10
      • 2013-04-19
      • 2018-12-20
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多