我有一个 JTree,其行为如下:
- 根有一个
RootObject
类型的用户对象;它使用纯文本标签,并且在树的整个生命周期中都是静态的。 - 每个子项都有一个
ChildObject
类型的用户对象,该对象可能处于以下三种状态之一:未运行、正在运行或已完成。 - 当
ChildObject
未运行时,它是一个纯文本标签。 - 当
ChildObject
运行时,它使用图标资源并切换到 HTML 渲染,因此文本为斜体。 - 当
ChildObject
完成后,它会使用不同的图标资源并使用 HTML 渲染以粗体显示文本。
目前,我的代码如下所示:
public class TaskTreeCellRenderer extends DefaultTreeCellRenderer {
private JLabel label;
public TaskTreeCellRenderer() {
label = new JLabel();
}
public Component getTreeCellRendererComponent(JTree tree,
Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Object nodeValue = ((DefaultMutableTreeNode) value).getUserObject();
if (nodeValue instanceof RootObject) {
label.setIcon(null);
label.setText(((RootObject) nodeValue).getTitle());
} else if (nodeValue instanceof ChildObject) {
ChildObject thisChild = (ChildObject) nodeValue;
if (thisChild.isRunning()) {
label.setIcon(new ImageIcon(getClass().getResource("arrow.png")));
label.setText("<html><nobr><b>" + thisChild.getName() + "</b></nobr></html>");
} else if (thisChild.isComplete()) {
label.setIcon(new ImageIcon(getClass().getResource("check.png")));
label.setText("<html><nobr><i>" + thisChild.getName() + "</i></nobr></html>");
} else {
label.setIcon(null);
label.setText(thisChild.getName());
}
}
return label;
}
}
在大多数情况下,这渲染得很好。初始树可以通过使用纯文本的标签呈现良好。问题是,一旦 ChildObject
实例开始更改状态,JLabels 就会更新为使用 HTML 渲染,但不会调整大小以补偿文本或图标。例如:
初始状态:
http://imageshack.us/a/img14/3636/psxi.png
进行中:
http://imageshack.us/a/img36/7426/bl8.png
已完成:
http://imageshack.us/a/img12/4117/u34l.png
有什么想法我哪里出错了吗?提前致谢!
最佳答案
所以你需要告诉树模型内容改变了。 每次如果您的 ChildObject 的状态发生更改,您必须执行以下操作:
((DefaultTreeModel)tree.getModel()).reload(node);
其中node
是DefaultMutableTreeNode
,其中包含更改后的ChildObject。
如果子对象的状态在 Swing 线程 (EDT) 之外发生更改,请不要忘记使用 SwingUtilities.invokeLater()。
关于java - 当内容更改时,JTree 中的 JLabel 不会调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19409465/