如何在 Java 中禁用 JTree 的叶子?
awtjavaobject oriented programmingprogrammingswing
JTree 是一个呈现数据 分层 视图的组件。用户可以 展开 或 折叠 单个子树。TreeNode 接口定义必须实现 JTree 对象节点的方法。DefaulMutableTreeNode 类提供 TreeNode 接口的默认实现。我们可以通过覆盖 DefaultTreeCellRenderer 类的 getTreeCellRendererComponent() 方法来禁用 JTree 的叶子。
语法
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
示例
import java.awt.*; import javax.swing.tree.*; import javax.swing.*; public class JTreeLeafNodeDisableTest extends JFrame { private TreeNode treeNode; private JTree tree; public JTreeLeafNodeDisableTest() { setTitle("JTreeLeafNodeDisable Test"); treeNode = new DefaultMutableTreeNode("Country"); tree = new JTree(); tree.setModel(new DefaultTreeModel(treeNode)); tree.setCellRenderer(new CustomDefaultTreeCellRenderer()); add(tree); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JTreeLeafNodeDisableTest(); } static class CustomDefaultTreeCellRenderer extends DefaultTreeCellRenderer { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { boolean enabled = false; sel = enabled; hasFocus = enabled; Component treeCellRendererComponent = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); treeCellRendererComponent.setEnabled(enabled); return treeCellRendererComponent; } } }