I am trying to make a small HTML-wysiwyg with a JTextPane
but I can\'t get the BackgroundAction
to work. I am using setCharacterAttributes
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();
}