我目前正在使用其中包含 html 的 JTextPane。我将其内容类型设置为 html 并且一切正常......或者我认为。
JTextPane 的功能是输出段落(带有
标签),每个段落有不同的颜色。每组
标签都带有内联样式属性。
现在我打印
标签是这样的:
String myLine = "<P style=\"color:blue;" +
"padding-left:25px;" +
"text-indent:-25px;" +
"font-family:Courier New;" +
"font-size:11;" +
"\">" ;
doc.insertBeforeEnd(body, myLine);
其中doc是JTextPane的JTextPane HTMLDocument,body是我的HTMLDocument中的body元素。
它在 JTextPane 中输出一切都很好,文本是蓝色的,courier,11 号大小,带有悬挂缩进。完美!
您会认为,如果您再次恢复文本,您会看到 P 标签与您构建它的方式相同。所以我使用 getText() 方法恢复其中的 html: 现实
<p style="text-indent: -25px; padding-left: 25px">
当我真正期待看到这个时: 期待
<p style="color:blue; text-indent: -25px; padding-left: 25px; font-family:Courier New; font-size:11;">
为什么要这样做?有没有办法避免这种情况?如果非要我猜的话,似乎 Java 提取了文本属性,以便它可以通过自己的方式更有效地处理这些属性。
但是,我问这个问题的原因是,一旦我开始更深入地自定义 JTextPane,着色就开始变得不可靠。我宁愿直接在内联样式上使用属性。
提前致谢,非常感谢您的帮助。
编辑:有人要求在添加
标签之前和之后查看完整的 html 输出。
之前:
<html>
<head>
</head>
<body>
</body>
</html>
现在我在 java 中执行这段代码:
String htmlLine = "<p style=\"color:blue; " +
"text-indent: -25px; " +
"padding-left: 25px; " +
"font-family:Courier New; " +
"font-size:11;\" >" ;
try {
doc.insertBeforeEnd(body, htmlLine);
} catch (Exception e) {
System.err.println(e);
}
之后:
<html>
<head>
</head>
<body>
<p style="text-indent: -23px; padding-left: 25px">
First Text
</p>
</body>
</html>
最佳答案
根据 insertBeforeEnd()
的 Java 文档
Unlike the insertAfterEnd method, new elements become children of the specified element, not siblings.
表示插入的元素正在成为子元素并继承其父元素的样式。在插入时,HTMLDocument 在内部从父级已经存在的子级中删除重复的样式信息。所以这就是你得到的原因
<p style="text-indent: -25px; padding-left: 25px">
代替
<p style="color:blue;
text-indent: -25px;
padding-left: 25px;
font-family: Courier New;
font-size:11;" >
你的情况最后的原因是
- 您已经为父项设置了相同的样式。
关于java - 带有 HTML 的 JTextPane,为什么有选择地删除某些内联样式属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14546437/