我使用Java swing来生成文本编辑器,使用JTextPane
,但我发现StyledEditorKit class
没有设置背景颜色的方法。
然后我用这个想法来设置背景颜色:
SimpleAttributeSet aSet = new SimpleAttributeSet();
StyleConstants.setBackground(aSet, color);
StyledDocument doc = textPane.getStyledDocument();
doc.setCharacterAttributes(textPane.getSelectionStart(),textPane.getSelectionEnd()-textPane.getSelectionStart(), aSet, false);
它可以在JTextPane
中显示背景颜色,
但不是textPane.GetText()
获取HTML代码。
然后我也发现了一个想法:
class bgAction extends StyledEditorKit.StyledTextAction {
public bgAction(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
@Override
public void actionPerformed(ActionEvent arg0) {
JEditorPane editor = getEditor(arg0);
try {
String selectedText = editor.getSelectedText();
HTMLDocument document = (HTMLDocument) this.getStyledDocument(editor);
System.out.println(document == TextView.this.document);
document.remove(editor.getSelectionStart(),selectedText.length());
HTMLEditorKit et = (HTMLEditorKit) this.getStyledEditorKit(editor);
et.insertHTML(document, editor.getSelectionStart(), ""+ selectedText + "", 0, 0, HTML.Tag.SPAN);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
但是insertHTML()
方法不起作用。
这是我出错的地方吗?
有没有办法在JTextPane
中设置背景颜色并获取HTML代码?
答案 0 :(得分:-1)
使用此代码段
JTextPane p=new JTextPane();
p.setContentType("text/html");
p.setStyledDocument(new HTMLDocument());
frame.getContentPane().add(p);
p.setText("<html><p>This is some text in a paragraph.</p></html>");
System.out.println(p.getText());