JLabel 中的多行文本
如何使 JLabel 的文本延伸到另一行?
How can I make the text of a JLabel extend onto another line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何使 JLabel 的文本延伸到另一行?
How can I make the text of a JLabel extend onto another line?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(11)
您可以通过将 HTML 放入代码中来完成此操作,因此:
You can do it by putting HTML in the code, so:
如果您希望 jLabel 文本自动调整大小,例如在可拉伸的 gridbaglayout 中,只需将其文本放入 html 标签中就足够了,如下所示:
if you want your jLabel Text to resize automaticly for example in a stretchable gridbaglayout its enough just to put its text in html tags like so:
我已将 JTextArea 用于多行 JLabels。
http://docs.oracle.com/javase/7 /docs/api/javax/swing/JTextArea.html
I have used JTextArea for multiline JLabels.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html
您还可以使用 SwingX 库。
You can also use a JXLabel from the SwingX library.
在
标记内键入内容(即“文本”属性字段)。 因此,您可以使用
或插入换行符。
例如:
显示如下:
一闪一闪,小星星,
我多么想知道你是什么。
高于世界如此之高,
就像天空中的一颗钻石。
Type the content (i.e., the "text" property field) inside a
<html></html>
tag. So you can use<br>
or<P>
to insert a newline.For example:
It will display as follows:
Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.
这太可怕了。 所有这些答案都建议添加到标签文本的开头,并且 Java 11(或更早版本)的 JLabel 文档中没有任何一个词表明如果标签的文本恰好以
开头,则会以不同的方式处理标签的文本
. 谁说这在任何地方都有效并且永远有效? 将任意文本包装起来并将其交给 html 布局引擎,您可以获得巨大的惊喜。我已经对建议 JTextArea 的答案投了赞成票。 但我要指出的是,JTextArea 并不是一个简单的替代品;它只是一个替代品。 默认情况下,它会扩展以填充行,这不是 JLabel 的行为方式。 我还没有想出解决办法。
This is horrifying. All these answers suggesting adding to the start of the label text, and there is not one word in the Java 11 (or earlier) documentation for JLabel to suggest that the text of a label is handled differently if it happens to start with
<html>
. Who says that works everywhere and always will? And you can get big, big surprises wrapping arbitrary text in and handing it to an html layout engine.I've upvoted the answer that suggests JTextArea. But I'll note that JTextArea isn't a drop-in replacement; by default it expands to fill rows, which is not how JLabel acts. I haven't come up with a solution to that yet.
就我而言,在每个
\n
处分割文本就足够了,然后为每一行创建一个JLabel
:我在上面的
JOptionPane.showMessageDialog
In my case it was enough to split the text at every
\n
and then create aJLabel
for every line:I used above in a
JOptionPane.showMessageDialog
您可以使用 JTextArea 并删除编辑功能来获取正常的只读多行文本。
JTextArea
setEditable
You can use
JTextArea
and remove editing capabilities to get normal read-only multiline text.JTextArea
setEditable
可以在 HTML 中使用(基本)CSS。
这个问题是从 Multiline JLabels - Java 链接的。
It is possible to use (basic) CSS in the HTML.
This question was linked from Multiline JLabels - Java.
为什么你要给出复杂的东西......你可以通过放置“\n”而不是 html 标签来做到这一点
why you are giving complex things...you can just do it by putting "\n" instead of html tags