Java JTextPane文本背景色不起作用

Java JTextPane文本背景色不起作用,java,swing,background-color,jtextpane,styleddocument,Java,Swing,Background Color,Jtextpane,Styleddocument,我正试图用JTextPane制作一个小的HTML所见即所得,但是背景动作无法正常工作。我正在JTextPane的StyledDocument上使用setCharacterAttributes,但它似乎有问题。视图正常,但文档不正常 下面是一个小的演示代码,显示了这个问题。有2个JTextPane: 我在第一个文本中设置了文本的背景色 我检索第一个JTextPane的文本,并将其设置在第二个上 -->虽然它们有相同的文本,但它们不显示相同的内容 是否有办法设置当前选定文本的背景色,并让JTextP

我正试图用
JTextPane
制作一个小的HTML所见即所得,但是
背景动作
无法正常工作。我正在
JTextPane
StyledDocument
上使用
setCharacterAttributes
,但它似乎有问题。视图正常,但
文档不正常

下面是一个小的演示代码,显示了这个问题。有2个
JTextPane

  • 我在第一个文本中设置了文本的背景色
  • 我检索第一个
    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();
                }
            });
        }
    
    }
    
    导入java.awt.Color;
    导入java.awt.GridBagConstraints;
    导入java.awt.GridBagLayout;
    导入javax.swing.JFrame;
    导入javax.swing.JPanel;
    导入javax.swing.JTextPane;
    导入javax.swing.SwingUtilities;
    导入javax.swing.text.SimpleAttributeSet;
    导入javax.swing.text.StyleConstants;
    导入javax.swing.text.StyledDocument;
    公共类TestDifferentStyles{
    私有void initUI(){
    JFrame=newjframe(TestDifferentStyles.class.getSimpleName());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    最终JTextPane textPane=新JTextPane();
    最终JTextPane textPane2=新JTextPane();
    textPane2.setEditable(false);
    setContentType(“text/html”);
    setContentType(“text/html”);
    textPane.setText(“helloworld

    ”); SimpleAttributeSet=新的SimpleAttributeSet(); setForeground(set,Color.GREEN); StyleConstants.setBackground(set,Color.BLACK); ((StyledDocument)textPane.getDocument()).setCharacterAttributes(0,textPane.getDocument().getLength(),set,false); JPanel panel=newjpanel(newgridbagloayout()); GridBagConstraints gbc=新的GridBagConstraints(); gbc.fill=GridBagConstraints.BOTH; gbc.weightx=1.0; gbc.weighty=1.0; panel.add(文本窗格,gbc); 面板.添加(文本窗格2,gbc); 框架。添加(面板); 框架。设置尺寸(500400); frame.setVisible(true); SwingUtilities.invokeLater(新的Runnable(){ @凌驾 公开募捐{ System.err.println(textPane.getText()); textPane2.setText(textPane.getText()); } }); } 公共静态void main(字符串[]args){ javax.swing.SwingUtilities.invokeLater(新的Runnable(){ @凌驾 公开募捐{ 新的TestDifferentStyles().initUI(); } }); } }
    输出结果(黑色边框围绕每个
    JTextPane
    ):

    以下是可设置背景颜色的操作代码:

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

    必须等待@Stanislav,他有覆盖照料者、选择和HightLighter的解决方案,我想这是关于UImanager及其XXX资源的,@mKorbel好的,谢谢。我将等待StanislavL:-)另请参阅Charles Bell的
    HTMLDocumentEditor
    ,引用。@trashgod实际上我正在重用中期编辑器,但他们的背景动作模糊,无法正常工作,因此我尝试修复它。我在您的示例中找不到
    BackgroundColorAction
    ,但中期是基于类似的东西的。@trashgod是的(我们不得不对其进行了很多调整,不幸的是,该项目看起来不太活跃),但是。感谢您的评论和欢呼;-)无法为
    Util
    类找到合适的包,并且它似乎不是字段。你能解释一下这行中“Util”指的是什么吗:
    Util.getHTMLColor(color)
    @NickRippe我还没有时间验证代码(将尽快验证),但我猜它会这样做:
    “#”+String.format(“%1$02x%2$02x%3$02x”、color.getRed()、color.getGreen()、color.getBlue())
    刚刚验证了它,它就像一个符咒+1并接受了答案。谢谢,我找到了答案,设置了很长时间的背景色,终于找到了正确的答案!