一、设置树节点的背景色
设置树的渲染器,方法如下:
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
setBackgroundNonSelectionColor(Color.LIGHT_GRAY);
return this;
}
二、设置节点的高度
1、 每个节点的高度相同且为20像素
setRowHeight(20);
2、 每个节点的高度根据实际情况而定
setRowHeight(0);
三、展开/折叠所有节点
代码如下:
public void ecTreeTest(JTree tree) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
expandTree(tree, new TreePath(root));
}
private void expandTree(JTree tree, TreePath parent) {
TreeNode node = (TreeNode) parent.getLastPathComponent();
if (node.getChildCount() >= 0) {
for (Enumeration<?> e = node.children(); e.hasMoreElements();) {
TreeNode n = (TreeNode) e.nextElement();
TreePath path = parent.pathByAddingChild(n);
expandTree(tree, path);
}
}
tree.expandPath(parent);
}
如上代码是展开树的所有节点,如果要折叠所有节点,只需把tree.expandPath(parent);改为tree.collapsePath(parent);即可。