【问题标题】:String as a JLabel name字符串作为 JLabel 名称
【发布时间】:2015-09-17 03:30:24
【问题描述】:

我正在遍历一个 ArrayList,并且我想为其中的每个值创建新的 JLabel。 JLable 名称应该是我列表中的一个值。

ArrayList<String> fieldsList = new ArrayList<String>();

for (int numberOfFields = 0; numberOfFields <= fieldsList.size(); numberOfFields++) {

        String fieldName = fieldsList.get(numberOfFields);

        JLabel "value from list"= new JLabel(fieldName + ":"); //here, in "" the name of JLabel should be the same as fieldName

    }

可能有一个简单的解决方案,但我找不到它

【问题讨论】:

  • 你做不到..那有什么用??
  • 当我在问题中看到“获取或分配变量名”时,我总是感到畏缩。变量“名称”并不是那么重要,许多对象都不存在,并且几乎不存在于编译代码中。如果一个对象被多个变量引用,哪一个代表这个对象的“名称”?
  • 更重要的是 object references 以及如何获得它们。如果您必须将对象与字符串相关联,一种简洁的方法是使用 Map,例如 HashMap&lt;String, MyType&gt; 或 HashMap&lt;MyType, String&gt;,具体取决于您希望将其用作键,但同样不要放太多依赖变量名,因为非最终变量可以随时更改引用,并且对象可以被多个变量引用。

标签: java string swing


【解决方案1】:

你不能这样做。另一种方法是创建 jlabel 列表

ArrayList<String> fieldsList = new ArrayList<String>();

JLabel[] lablearr=new JLabel[fieldsList.size()]; //lable array

for (int numberOfFields = 0; numberOfFields < fieldsList.size(); numberOfFields++) {

        String fieldName = fieldsList.get(numberOfFields);

        lablearr[numberOfFields]= new JLabel(fieldName + ":"); 

 }

现在如果你想调用特定的 jlabel,你可以使用

  lablearr[i]

例如,如果您要调用名称为 mylable: 的 jlable,则循环遍历数组列表 - fieldsList 并找到“mylable”的索引并通过该索引调用 jlable。

【讨论】:

    【解决方案2】:

    这就是我的做法:

    for (String fieldName : fieldsList) {
            {
                {
                    JLabel lbl = new JLabel(fieldName + ":");
                    lbl.setBounds(33, counter, 130, 14);
                    getContentPane().add(lbl);
                }
                counter += 25;
            }
        }
    

    对我有用

    【讨论】:

      猜你喜欢
      • 2011-09-05
      • 2011-07-13
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 2013-12-03
      • 2019-08-20
      相关资源
      最近更新 更多