欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解决JTextPane设定其Background颜色无法导出正确的HTML的问题

程序员文章站 2022-07-08 15:51:05
...
设定foreground代码如下:
SimpleAttributeSet textColour = new SimpleAttributeSet();
StyleConstants.setForeground(textColour, Colors.RED);
textPane.setCharacterAttributes(textColour, false);
可以正常导出正确的HTML文本,但是直接修改setForeground为setBackground,是无法导出正确的HTML文本的。

workaround的原链接在此:
https://*.com/questions/13285526/jtextpane-text-background-color-does-not-work

以上代码修改为:
String htmlStyle = "background-color:"+ getHTMLColor(Colors.RED);
SimpleAttributeSet textColour = new SimpleAttributeSet();
textColour.addAttribute(HTML.Attribute.STYLE, htmlStyle);
MutableAttributeSet outerAttr = new SimpleAttributeSet();
outerAttr.addAttribute(HTML.Tag.SPAN, textColour);
StyleConstants.setBackground(outerAttr, backgroundColors.getSelectedItem().c);
StyleConstants.setBackground(textColour, backgroundColors.getSelectedItem().c);
textPane.setCharacterAttributes(outerAttr, false);
textPane.setCharacterAttributes(textColour, false);
其中:
public static String getHTMLColor(Color color) {
if (color == null) {
return "#000000";
}
return "#" + Integer.toHexString(color.getRGB()).substring(2).toUpperCase();
}
导出的HTML增加了一节:
<span style="background-color:#FF0000">
解决此问题