gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:40:01 24 4
gpt4 key购买 nike

一个简单的 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);
}

最佳答案

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.

关于java - 不同的 JEditorPanes 显示 html 内容,使用相同的 css 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33780582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com