How to add text to JLabel

假如想象 提交于 2019-12-24 11:21:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!