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

设定foreground代码如下: SimpleAttributeSet textColour = new SimpleAttributeSet(); StyleConstants.setForeground(textColour, Colors.RED); textPane.setCharacterAttributes(textColo...
设定foreground代码如下:
SimpleAttributeSet textColour = new SimpleAttributeSet();
StyleConstants.setForeground(textColour, Colors.RED);
textPane.setCharacterAttributes(textColour, false);
可以正常导出正确的HTML文本,但是直接修改setForeground为setBackground,是无法导出正确的HTML文本的。

workaround的原链接在此:
https://stackoverflow.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">
解决此问题

原文出处:http://stjauns.iteye.com/blog/2425653

  • 发表于 2018-09-17 21:48
  • 阅读 ( 293 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除