问题
I am creating a book reader, which takes the content of a file and sends it to an Object[]. I want this to be displayed, line by line on my page. I'm considering a loop of some sort that will add text to the label, but here's my question: How to I add text to the end of a JLabel, rather than setting the whole thing?
回答1:
You can use getText()
to retrieve what's there, and then setText()
to set the new value.
So to add something
to the end, you'd do
label.setText(label.getText()+"something");
Remember you'll probably be wanting to add a space in the middle. If you've got a new String str
you want to append, you will probably want
label.setText(label.getText()+" "+str);
to make sure you add the space and then the contents of str
.
回答2:
@chiastic-security answer is the better one. Here is another solution that I believe will save some memory.
StringBuilder sb = new StringBuilder();
Object[] objectArray;
for (Object o : objectArray) { // loop through the Object array
sb.append(o.toString() + " "); // append each index of the Object array to the StringBuilder
}
label.setText(sb.toString());
来源:https://stackoverflow.com/questions/27624270/how-to-add-text-to-jlabel