Java swing:多行标签?
可能的重复:
JLabel 中的多行文本
我想这样做:
JLabel myLabel = new JLabel();
myLabel.setText("This is\na multi-line string");
标签
This isa multi-line string
目前这会导致显示我想要的 而是这样做:
This is
a multi-line string
有什么建议吗?
谢谢
编辑:已实现的解决方案
在方法正文中:
myLabel.setText(convertToMultiline("This is\na multi-line string"));
辅助方法:
public static String convertToMultiline(String orig)
{
return "<html>" + orig.replaceAll("\n", "<br>");
}
Possible Duplicate:
Multiline text in JLabel
I want to do this:
JLabel myLabel = new JLabel();
myLabel.setText("This is\na multi-line string");
Currently this results in a label that displays
This isa multi-line string
I want it to do this instead:
This is
a multi-line string
Any suggestions?
Thank you
EDIT: Implemented solution
In body of method:
myLabel.setText(convertToMultiline("This is\na multi-line string"));
Helper method:
public static String convertToMultiline(String orig)
{
return "<html>" + orig.replaceAll("\n", "<br>");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以在
JLabels
中使用HTML
。要使用它,您的文本必须以开头。
将文本设置为
“这是
,它应该可以工作。多行字符串”
请参阅 Swing 教程:JLabel 和多行标签 (HTML) 了解更多信息。
You can use
HTML
inJLabels
. To use it, your text has to start with<html>
.Set your text to
"<html>This is<br>a multi-line string"
and it should work.See Swing Tutorial: JLabel and Multiline label (HTML) for more information.
对我来说看起来完全一样,但很丑
It totally looks the same for me, but its ugly
另一种简单的方法(但稍微改变文本样式)是使用
html 块。
如果您使用的字符串来自用户输入框,这将保留用户输入的任何格式。
例子:
Another easy way (but changes the text style a bit) is to use a
<pre></pre>
html block.This will persist any formatting the user entered if the string you are using came from a user input box.
Example:
在 jlabel 中写入多行文本的直接过程是:
The direct procedure of writing a multi-line text in a jlabel is:
在
JLabel
或任何 Swing 组件中使用 html 的问题是,您必须将其样式设置为 html,而不是使用通常的setFont
、setForeground
等等。如果你同意的话,那就好。否则,您可以使用 JIDE 中的 MultilineLabel 之类的内容,它扩展了 <代码>JTextArea。它是他们的开源公共层的一部分。
The problem with using html in
JLabel
or any Swing component is that you then have to style it as html, not with the usualsetFont
,setForeground
, etc. If you're ok with that, fine.Otherwise you can use something like MultilineLabel from JIDE, which extends
JTextArea
. It's part of their open source Commom Layer.JLabel可以接受html代码。也许您可以尝试使用
标签。例子:
JLabel can accept html code. Maybe you can try to use the
<br>
tag.Example:
http://java.sun.com/docs/books/教程/uiswing/components/html.html
http://java.sun.com/docs/books/tutorial/uiswing/components/html.html