我正在尝试使用 aJTextPane
来呈现一些 HTML 并向其应用 CSS 样式表。这意味着我正在使用HTMLEditorKit
和StyleSheet
类。我知道它们都HTMLEditorKits
共享相同的默认StyleSheet
实例,因此如果您更改此默认样式表对象,您将在应用程序级别应用更改(所有呈现 HTML 的组件)。
但在我的示例中,我认为我已经通过StyleSheet
基于默认值创建自己的实例来避免这种情况。但是,这不起作用,正如显示的JTree
那样,它按照样式表呈现,该样式表仅适用于JTextPane
.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.html.*;
import javax.swing.tree.*;
public class TextPaneCssSpill extends JFrame {
private JTextPane textPane;
private JTree tree;
private JSplitPane splitPane;
public TextPaneCssSpill() {
HTMLEditorKit hed = new HTMLEditorKit();
StyleSheet defaultStyle = hed.getStyleSheet();
StyleSheet style = new StyleSheet();
style.addStyleSheet(defaultStyle);
style.addRule("body {font-family:\"Monospaced\"; font-size:9px;}");
style.addRule("i {color:#bababa; font-size:9px;}"); // gray italic
hed.setStyleSheet(style);
textPane = new JTextPane();
textPane.setEditorKit(hed);
textPane.setDocument(hed.createDefaultDocument());
DefaultMutableTreeNode root = new DefaultMutableTreeNode(new MyNode("name", "argument"), true);
root.add(new DefaultMutableTreeNode(new MyNode("name", "argument"), false));
root.add(new DefaultMutableTreeNode(new MyNode("name", "argument"), false));
root.add(new DefaultMutableTreeNode(new MyNode("name", "argument"), false));
root.add(new DefaultMutableTreeNode(new MyNode("name", "argument"), false));
tree = new JTree(root);
tree.setCellRenderer(new MyNodeTreeRenderer());
setLayout(new BorderLayout());
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, textPane, tree);
add(splitPane);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TextPaneCssSpill().setVisible(true);
}
});
}
private static class MyNode {
private final String name;
private final String argument;
public MyNode(String name, String argument) {
this.name = name;
this.argument = argument;
}
@Override
public String toString() {
return name + " " + argument;
}
}
private static class MyNodeTreeRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (value instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
if (node.getUserObject() instanceof MyNode) {
MyNode mynode = (MyNode) node.getUserObject();
setText("<html>" + mynode.name + " <i>" + mynode.argument);
}
}
return this;
}
}
}
那么如何正确地初始化这些对象,以使应用程序中没有 CSS 溢出(这样文本窗格根据 CSS 呈现,而树没有)?
注意:上图中红色下划线表示溢出问题,是我后来添加的(不是,不是渲染器)。