Java 如何将文本添加到 JLabel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27624270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:43:50  来源:igfitidea点击:

How to add text to JLabel

javajlabel

提问by CaffeineToCode

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?

我正在创建一个图书阅读器,它获取文件的内容并将其发送到 Object[]。我希望在我的页面上逐行显示。我正在考虑将文本添加到标签的某种循环,但这是我的问题:如何将文本添加到 JLabel 的末尾,而不是设置整个内容?

采纳答案by chiastic-security

You can use getText()to retrieve what's there, and then setText()to set the new value.

您可以使用getText()来检索那里的内容,然后setText()设置新值。

So to add somethingto the end, you'd do

所以要添加something到最后,你会做

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 stryou want to append, you will probably want

请记住,您可能希望在中间添加一个空格。如果你有一个新的String str想要追加,你可能会想要

label.setText(label.getText()+" "+str);

to make sure you add the space and then the contents of str.

确保添加空格,然后添加str.

回答by Arc

@chiastic-security answer is the better one. Here is another solution that I believe will save some memory.

@chiastic-security 答案是更好的答案。这是我认为可以节省一些内存的另一种解决方案。

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