A simple swing application uses two independent JDialogs that contain different JEditorPanes with different html content. In one JEditorPane we use css rules to display the borders of a table. But another JEditorPane uses the same css rules and draws the border of the 3px table, but it should not (we do not set it explicitly). Why do they use the same CSS rules and how can we fix this?
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: As Freek de Bruijn said, this is not a mistake, and it is documented. Therefore, when we install or get a StyleSheet in an HTMLEditorKit, it uses the StyleSheet from the AppContext and therefore shares the StyleSheet between all instances of HTMLEditorKit, so the only way to solve this problem is to override the HTMLEditorKit methods. I did it as follows:
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; } }
And now the setCSS method looks like this:
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); }
source share