英文:
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<5; i++){
JLabel newlabel = new JLabel();
newlabel.setText("somekindoftext");
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<JLabel>
, that is a field of your class:
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); // <-----
}
Now you can refer to the labels as labels.get(0)
, labels.get(1)
, labels.get(2)
etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论