5
一个简单的swing应用程序绘制两个独立的JDialogs,其中包含具有不同html内容的不同JEditorPanes。在一个JEditorPane中,我们使用css规则来设置表格的边框可见。但另一个JEditorPane使用相同的css规则并绘制3px表格边框,但它不应该(我们没有明确设置)。为什么他们使用相同的css规则以及我们如何修复它?不同的JEditorPanes显示html内容,使用相同的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:由于暴走德布鲁因说,这是不是一个错误,它被记录在案。因此,当我们在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);
}
非常感谢你!我刚刚将setCSS方法的第一行修改为“StyleSheet styleSheet = new StyleSheet();”。不正常。谢谢! – shiv
不错,解决方案非常简单! –
我太急于说它昨天解决了一切。今天,当我试图将解决方案转移到真正的应用程序时,我注意到了它 - 现在它的工作原理与它应该相反,所以第一个对话框没有边框(但它应该),其次是边框(但不应该)。无论如何,感谢你,我得到了解决问题的线索,经过一番调查,我设法解决了这个问题。我更新了我的帖子以显示我的解决方案。 – shiv