java swing中的JTree组件

发布于 2024-08-23 00:08:03 字数 50 浏览 4 评论 0原文

如何更改 Swing 的 JTree 组件中节点和根的图标?

How can I change the icon of nodes and root in the JTree component of Swing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

jJeQQOZ5 2024-08-30 00:08:03

使用 DefaultTreeCellRenderer 使用setClosedIconsetOpenIconsetLeafIcon

复制自如何使用树

ImageIcon leafIcon = createImageIcon("images/middle.gif");
if (leafIcon != null) {
    DefaultTreeCellRenderer renderer = 
    new DefaultTreeCellRenderer();
    renderer.setLeafIcon(leafIcon);
    tree.setCellRenderer(renderer);
}

With a DefaultTreeCellRenderer use setClosedIcon, setOpenIcon and setLeafIcon.

Copied from How to Use Trees:

ImageIcon leafIcon = createImageIcon("images/middle.gif");
if (leafIcon != null) {
    DefaultTreeCellRenderer renderer = 
    new DefaultTreeCellRenderer();
    renderer.setLeafIcon(leafIcon);
    tree.setCellRenderer(renderer);
}
西瓜 2024-08-30 00:08:03

Sun 的关于 JTree 的 教程 有一节介绍了如何子类 TreeCellRenderer 以获取 JTree 中的节点和文本。

Sun's Tutorial on JTree has a section on how to subclass TreeCellRenderer to get nodes and text in a JTree.

只怪假的太真实 2024-08-30 00:08:03

如果您想要做的只是为闭合节点、叶子和打开节点使用不同的图标,那么这非常简单。

//创建3个图标
私有图标 customOpenIcon = new ImageIcon("images/my_open.gif");
私有图标 customClosedIcon = new ImageIcon("images/my_close.gif");
私有图标 customLeafIcon = new ImageIcon("images/my_leaf.gif");

//假设您创建了 DefaultMutableTreeNode 层次结构
DefaultMutableTreeNode rootNode = 新...
...
JTree 树 = new JTree(rootNode );

DefaultTreeCellRenderer customRenderer = new DefaultTreeCellRenderer();
customRenderer.setOpenIcon(customOpenIcon);
customRenderer.setClosedIcon(customClosedIcon);
customRenderer.setLeafIcon(customLeafIcon);
tree.setCellRenderer(customRenderer );

If all you trying to do is to have different Icons for closed node, leaf and opened nodes, it is very straight forward.

//Create 3 icons
private Icon customOpenIcon = new ImageIcon("images/my_open.gif");
private Icon customClosedIcon = new ImageIcon("images/my_closed.gif");
private Icon customLeafIcon = new ImageIcon("images/my_leaf.gif");

//Assuming you created your DefaultMutableTreeNode hierarchy
DefaultMutableTreeNode rootNode = new...
...
JTree tree = new JTree(rootNode );

DefaultTreeCellRenderer customRenderer = new DefaultTreeCellRenderer();
customRenderer.setOpenIcon(customOpenIcon);
customRenderer.setClosedIcon(customClosedIcon);
customRenderer.setLeafIcon(customLeafIcon);
tree.setCellRenderer(customRenderer );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文