JTextPane文本背景颜色无法工作

6
我正在尝试使用JTextPane制作一个小型的HTML所见即所得编辑器,但我无法使BackgroundAction起作用。我在JTextPaneStyledDocument上使用了setCharacterAttributes,但似乎存在问题。视图是正常的,但Document不是。

以下是显示问题的小型演示代码,其中包含2个JTextPane

  1. 我在第一个文本框中设置了文本的背景颜色
  2. 我获取了第一个JTextPane的文本,并将其设置到第二个文本框中

    --> 虽然它们具有相同的文本,但它们显示的内容不同。

是否有一种方法可以在当前选择的文本上设置背景颜色,并让JTextPane报告更新后的HTML文本?

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class TestDifferentStyles {

    private void initUI() {
        JFrame frame = new JFrame(TestDifferentStyles.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextPane textPane = new JTextPane();
        final JTextPane textPane2 = new JTextPane();
        textPane2.setEditable(false);
        textPane.setContentType("text/html");
        textPane2.setContentType("text/html");
        textPane.setText("<html><head></head><body><p>Hello world</p></body></html>");
        SimpleAttributeSet set = new SimpleAttributeSet();
        StyleConstants.setForeground(set, Color.GREEN);
        StyleConstants.setBackground(set, Color.BLACK);
        ((StyledDocument) textPane.getDocument()).setCharacterAttributes(0, textPane.getDocument().getLength(), set, false);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        panel.add(textPane, gbc);
        panel.add(textPane2, gbc);
        frame.add(panel);
        frame.setSize(500, 400);
        frame.setVisible(true);
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                System.err.println(textPane.getText());
                textPane2.setText(textPane.getText());
            }
        });
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestDifferentStyles().initUI();
            }
        });
    }

}

输出结果(每个JTextPane周围都有黑色边框): output result

必须等待@Stanislav,他有关于覆盖Carer、Selections和HightLighter的解决方案,我认为这与UImanager及其XxxResources有关。 - mKorbel
@mKorbel 好的,谢谢。我会等 StanislavL 的 :-) - Guillaume Polet
另请参见查尔斯·贝尔(Charles Bell)的HTMLDocumentEditor,引用此处 - trashgod
@trashgod,实际上我正在重复使用Metaphase编辑器,但是他们的BackgroundAction模糊不清,而且无法正常工作,所以我尝试修复它。在您的示例中,我找不到BackgroundColorAction,但Metaphase基于类似的东西。 - Guillaume Polet
啊,Metaphase Editor,在这里引用链接。你可以在这个问题中链接到它,以供将来的访问者使用。 - trashgod
1
@trashgod没错(我们不得不对它进行了很多调整,不幸的是,该项目看起来并不太活跃),但是这是metaphase编辑器网站的链接。感谢您的评论和加油;-) - Guillaume Polet
1个回答

5

这里是一个可以设置背景颜色的 Action 代码:

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

我曾经在设置背景颜色时遇到了很多麻烦。但最终,我成功地解决了这个问题。

抱歉,我忘记发布子程序了。下面是代码:

/**  
 * 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();
}

找不到适合 Util 类的包,也似乎不是一个字段。你能否解释一下在这行代码中 'Util' 是指什么:Util.getHTMLColor(color); - Nick Rippe
@NickRippe 我还没有时间验证这段代码(尽快会验证),但我猜它大概是像这样的:"#" + String.format("%1$02x%2$02x%3$02x", color.getRed(), color.getGreen(), color.getBlue()) - Guillaume Polet
刚刚验证了一下,它完美地运行了。+1并接受答案。 - Guillaume Polet
谢谢,我寻找如何设置背景颜色已经很长时间了,终于找到正确的方法了! - oliver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接