JTextPane text background color does not work

我们两清 提交于 2019-11-29 07:30:14
pratap triapthy

Here is the code for an Action that can set the background color:

public class BackgroundColorAction extends StyledEditorKit.StyledTextAction {

    private Color color;

    public BackgroundColorAction(Color color) {
        super(StyleConstants.Background.toString());
        this.color = color;
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        JEditorPane editor = getEditor(ae);
        if (editor == null) {
            return;
        }
        //Add span Tag
        String htmlStyle = "background-color:" + Util.getHTMLColor(color);
        SimpleAttributeSet attr = new SimpleAttributeSet();
        attr.addAttribute(HTML.Attribute.STYLE, htmlStyle);
        MutableAttributeSet outerAttr = new SimpleAttributeSet();
        outerAttr.addAttribute(HTML.Tag.SPAN, attr);
        //Next line is just an instruction to editor to change color
        StyleConstants.setBackground(outerAttr, this.color);
        setCharacterAttributes(editor, outerAttr, false);
    }
}

I had lot of trouble setting background color. But finally, I have managed to crack it.` Sorry I forgot to post the subroutine. Here you go:

/**  
 * Convert a Java Color to equivalent HTML Color.
 *
 * @param color The Java Color
 * @return The String containing HTML Color.
 */
public static String getHTMLColor(Color color) {
    if (color == null) {
        return "#000000";
    }
    return "#" + Integer.toHexString(color.getRGB()).substring(2).toUpperCase();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!