不同的JEditorPanes显示html内容,使用相同的css规则

时间:2015-11-18 12:51:24

标签: java html css swing

一个简单的swing应用程序绘制了两个独立的JDialog,它们包含具有不同html内容的不同JEditorPanes。在一个JEditorPane中,我们使用css规则来设置表的边框可见。但另一个JEditorPane使用相同的css规则并绘制3px表边框,但它不应该(我们不明确设置它)。为什么他们使用相同的CSS规则以及我们如何解决它?

public static void main(String args[]) {
    String text1 = "<html><body><table><tr><td>somthing ONE</td></tr></table></body></html>";
    String text2 = "<html><body><table><tr><td>somthing TWO</td></tr></table></body></html>";

    JDialog jd = new JDialog();
    JEditorPane jep = new JEditorPane();
    HTMLEditorKit kit = new HTMLEditorKit();
    HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
    jep.setEditorKit(kit);
    jep.setDocument(doc);
    setCSS(kit);
    jep.setText(text1);
    jd.getContentPane().add(jep);
    jd.pack();  
    jd.setVisible(true);

    JDialog jd2 = new JDialog();
    JEditorPane jep2 = new JEditorPane();
    HTMLEditorKit kit2 = new HTMLEditorKit();
    HTMLDocument doc2 = (HTMLDocument) kit2.createDefaultDocument();
    jep2.setEditorKit(kit2);
    jep2.setDocument(doc2);
    //We do not install css rules explicitly here
    jep2.setText(text2);
    jd2.getContentPane().add(jep2);
    jd2.pack();
    jd2.setVisible(true);
}


public static void setCSS(HTMLEditorKit kit) {
    StyleSheet styleSheet = kit.getStyleSheet();
    styleSheet.addRule("td {border-width: 3px; border-style: solid; border-color: #000000;}");
    kit.setStyleSheet(styleSheet);
}
UPD:正如Freek de Bruijn所说,这不是一个错误,而是记录在案。因此,当我们在HTMLEditorKit中设置或获取StyleSheet时,它使用AppContext中的StyleSheet,因此它在HTMLEditorKit的所有实例之间共享StyleSheet,因此解决此问题的唯一方法是覆盖HTMLEditorKit的方法。我是这样做的:

public static class CustomKit extends HTMLEditorKit {
    private StyleSheet styles;

    @Override
    public void setStyleSheet(StyleSheet styleSheet) {
        styles = styleSheet;
    }
    @Override
    public StyleSheet getStyleSheet() {
        if (styles == null) {
            styles = super.getStyleSheet();
        }
        return styles;
    }
}

setCSS方法现在看起来像:

public static void setCSS(CustomKit kit) {
    StyleSheet styleSheet = new StyleSheet();
    styleSheet.addRule("td {border-width: 3px; border-style: solid; border-color: #000000;}");
    kit.setStyleSheet(styleSheet);
}

1 个答案:

答案 0 :(得分:1)

所有StyleSheet实例似乎共享HTMLEditorKit对象。来自HTMLEditorKit.getStyleSheet方法的Javadoc注释:

* Get the set of styles currently being used to render the
* HTML elements.  By default the resource specified by
* DEFAULT_CSS gets loaded, and is shared by all HTMLEditorKit
* instances.