---
title: "解决JTextPane设定其Background颜色无法导出正确的HTML的问题"
author: "stjauns"
date: "2018-06-26T18:09:00Z"
tags: ["HTML", "Java", "Swing", "jtextpane"]
categories: ["编程语言"]
slug: "jtextpane-background-html"
draft: false
lastmod: "2018-06-26T18:09:00Z"
id: 2425653
url: "https://stjauns.iteye.com/blog/2425653"
---

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