【发布时间】:2017-07-25 22:37:03
【问题描述】:
我有一个 JLabel,里面有一些 html 格式的文本。最终我试图在 JTable 中换行。但是,我的问题可以通过 JLabel 来简化。其中的 HTML 格式如下所示:
<html>
<body style='width: 250px;'>
<p style='word-wrap: break-word;'>some string</p>
</body>
</html>
在浏览器中运行它,一切都按预期工作,即使是一个很长的单字字符串,它也会按照我的意愿进行换行。如果我把它放在这样的 JLabel 中:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class HtmlInLabelExample extends JFrame {
private static final long serialVersionUID = 2194776387062775454L;
public HtmlInLabelExample() {
this.setTitle("HTML within a JLabel");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setSize(new Dimension(300, 100));
this.setLocationRelativeTo(null);
String HTML_1 = "<html><body style='width: ";
String HTML_2 = "px;'><p style='word-wrap: break-word;'>";
String HTML_3 = "</p></body></html>";
String strWithSpaces = "This is a long String that should be wrapped and displayed on multiple lines. However, if this was only one really long word, that doesnt work.";
String strWithoutSpaces = "ThisisalongStringthatshouldbewrappedanddisplayedonmultiplelines.However,ifthiswasonlyonereallylongword,thatdoesntwork.";
JLabel lblHtml = new JLabel();
lblHtml.setText(HTML_1 + String.valueOf(250) + HTML_2 + strWithoutSpaces + HTML_3);
this.add(lblHtml);
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new HtmlInLabelExample();
}
});
}
}
换行有效,但不会在单词之间中断,好像我不会使用 style='word-wrap: break-word;.
有人可以向我解释为什么 html 格式在浏览器中的工作方式不同(我尝试了最常见的)以及是否有解决方法?
【问题讨论】: