Various JEditorPanes show html content using the same css rules

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); } 
+5
source share
1 answer

It looks like the StyleSheet object StyleSheet used by all instances of HTMLEditorKit . From the Javadoc comment of the HTMLEditorKit.getStyleSheet method:

 * 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. 
+1
source

Source: https://habr.com/ru/post/1236227/


All Articles