修改在JFrame中的一组JLabel元素

huangapple go评论61阅读模式
英文:

Modify group of JLabel elements in a JFrame

问题

我想在将其添加到窗口后修改 JLabel

for(int i=0; i<5; i++){
    JLabel newlabel = new JLabel();
    newlabel.setText("某种文本");
    newlabel.setBounds(50, 50+(10*i), 150, 14);
    newlabel.setVisible(true);
    object.add(newlabel);
}

在将它们添加到窗口后,如何分别修改它们?

所以如果我有一个名为 modifyText() 的函数,如何访问标签,修改文本,然后重新绘制到面板上?

英文:

I want to modify a JLabel after added it to the frame.

for(int i=0; i&lt;5; i++){
	JLabel newlabel = new JLabel();
	newlabel.setText(&quot;somekindoftext&quot;);
	newlabel.setBounds(50, 50+(10*i), 150, 14);
	newlabel.setVisible(true);
	object.add(newlabel);
}

After I added them to the frame, how can U modify them separately?

So if I have a function called modifyText() how can I reach the labels, modify the text, and after it redraw it to the panel?

答案1

得分: 3

一种方法是将标签添加到您的类的一个字段中,该字段是一个 ArrayList<JLabel>

private ArrayList<JLabel> labels = new ArrayList<JLabel>();

...

for(int i=0; i<5; i++){
    JLabel newlabel = new JLabel();
    newlabel.setText("somekindoftext");
    newlabel.setBounds(50, 50+(10*i), 150, 14);
    newlabel.setVisible(true);
    object.add(newlabel);
    labels.add(newLabel); // <-----
}

现在您可以通过 labels.get(0)labels.get(1)labels.get(2) 等来引用这些标签。

英文:

One way to do this is to add your labels to an ArrayList&lt;JLabel&gt;, that is a field of your class:

private ArrayList&lt;JLabel&gt; labels = new ArrayList&lt;JLabel&gt;();

...

for(int i=0; i&lt;5; i++){
    JLabel newlabel = new JLabel();
    newlabel.setText(&quot;somekindoftext&quot;);
    newlabel.setBounds(50, 50+(10*i), 150, 14);
    newlabel.setVisible(true);
    object.add(newlabel);
    labels.add(newLabel); // &lt;-----
}

Now you can refer to the labels as labels.get(0), labels.get(1), labels.get(2) etc.

huangapple
  • 本文由 发表于 2020年4月8日 22:07:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/61102695.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定