【问题标题】:How to set the background color in the JTextPane and get the HTML code?如何在 JTextPane 中设置背景颜色并获取 HTML 代码?
【发布时间】:2013-08-03 05:09:14
【问题描述】:

我正在使用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代码?

【问题讨论】:

    标签: java swing background-color jtextpane


    【解决方案1】:

    使用这个代码sn-p

                         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());
    

    【讨论】:

    • 这段代码和我的第一个代码sn-p一样,可以在JTextPane中显示背景色,但是不能通过textPane.getText()获取HTML代码。
    • 使用 textPane.getDocument().getText() 之类的方法。
    • textPane.getDocument().getText() 只能获取文本,但我想获取 HTML 代码,而 textPane.getText() 可以。
    • 它与背景颜色有什么关系?
    • @StanislavL 他能够设置背景颜色。但他无法获取html代码。
    猜你喜欢
    • 2013-10-26
    • 2020-06-28
    • 2012-10-15
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2010-12-11
    • 1970-01-01
    相关资源
    最近更新 更多