简体   繁体   中英

How to add text to JLabel

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?

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 .

@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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM