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

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

public static void main(String args[]) {

String text1 = "

somthing ONE
";

String text2 = "

somthing TWO
";

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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值