ITeye博客

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

stjauns · 2018-06-26 18:09 · JAVA · 编程语言 · HTML · Java · Swing · jtextpane · Markdown

设定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增加了一节: 解决此问题

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。