style="display: none" 属性在 JTextPane 中不起作用

style="display: none" attribute not working in JTextPane

我正在使用 JTextPane 在 java 中创建一个 html 编辑器。属性 style = "display: none" 在这里似乎没有按预期工作。帮我出去。 我的代码是:

JTextPane basePane = new JTextPane(); 
basePane.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
basePane.setContentType("text/html");
basePane.setText("<html><body><p style=\"display: none\" >hello world!</p></body></html>");

字符串 "hello world!" 仍在打印中。 我尝试使用 div 标签并将 style="display: none" 属性放在那里。它在那里也不起作用。 帮我出去!

提前致谢! ;)

我认为如果要实现它,您需要创建自己的视图。 JTextPane中对CSS的支持是非常偏的

尝试这样的事情:

    //Create a view that inherites from InlineView and behave the way you want.
    //In your case, it should react to getAttributes().getAttribute(CSS.Attribute.DISPLAY);
    private class HideableView extends InlineView {
        public HideableView(Element elem) { super(elem); }
        //Implement your expected behaviour here
        @Override
        public void paint(Graphics g, Shape a){}
    }


    //Create a View Factory that will replace InlineViews by your custom View
    public static class HTMLBetterFactory extends HTMLEditorKit.HTMLFactory {
        @Override
        public View create(Element elem) {
            AttributeSet attrs = elem.getAttributes();
            Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
            Object o = (elementName != null) ? null : attrs.getAttribute(StyleConstants.NameAttribute);
            if (o == HTML.Tag.CONTENT) {
                if(attrs.getAttribute(CSS.Attribute.DISPLAY).toString().equals("none"))
                      return new HideableView(elem);
            }
            return super.create(elem);
        }
    }


//Create an HTMLEditorKit that will use your custom Factory
public class HTMLBetterEditorKit extends HTMLEditorKit {

    private final HTMLEditorKit.HTMLFactory factory = new HTMLBetterFactory();
        @Override
        public ViewFactory getViewFactory() {
            return factory;
        }
    }
}

//Import your HTMLEditorKit into your JTextPane
HTMLBetterEditorKit editorKit = new HTMLBetterEditorKit();
myJTextPane.setEditorKit(editorKit);

这是针对内联元素的,但您可以为其他元素重现该过程。

我的用例略有不同,但可能仍然与最终来到这里的其他人相关。我在 JLabel 中渲染一些 HTML 并想有条件地隐藏一些元素。我不需要任何动态可见性,所以我最终在 Java 中进行了预过滤,以防止我想要隐藏的元素进入 HTML 源。