如何修改 TreeCellEditor 的默认编辑行为 (Java)
我有一个自定义对象,它具有描述(字符串)和优先级值(整数)。我在 JTree 中显示这些值,因为这种类型的不同对象之间存在层次关系。我只显示 JTree 节点中的描述,因为优先级对于显示目的并不重要。
我希望在编辑 JTree 节点(叶或节点)时弹出 JDialog - 例如按 F2。然后,该对话框将用于编辑描述和优先级。
如何防止 JTree 将文本作为文本字段执行默认编辑并调用自定义对话框?
我认为一个简单的方法是对 DefaultTreeCellEditor 类进行子类化并重写 isCellEditable 方法。然后,我将在那里调用 JDialog(当我实例化自定义 DefaultTreeCellEditor 时,我可以获取相关的初始化元素)并简单地返回 false 以防止默认编辑 - 但这对我来说似乎不够优雅。
I have a custom object that has a description (String) and priority value (int). I display these values in a JTree because there is a hierarchical relationship between different objects of this type. I only display the description in the JTree nodes because the priority is not important for display purposes.
I would like to have a JDialog pop-up when I edit a JTree node (leaf or node) - for example by pressing F2. This dialog will then be used to edit both the description and the priority.
How do I prevent the JTree from performing the default editing of the text as a text field and call up the custom dialog instead?
An easy way I suppose would be to subclass the DefaultTreeCellEditor class and override the isCellEditable method. Then, I would invoke the JDialog there (I can obtain the relevant initialization elements when I instantiate the custom DefaultTreeCellEditor) and simply return false to prevent the default editing - but this to me doesn't seem elegant enough.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为替代方案,请考虑
org.netbeans.swing.outline.Outline
,此处进一步讨论。As an alternative, consider
org.netbeans.swing.outline.Outline
, discussed further here.我想 F2 适用于您的树节点,因为您调用了 JTree#setEditable(true)。
F2 绑定安装在
BasicTreeUI#installKeyboardActions
中。您可以按照通常的方式安装自己的绑定:JComponent.WHEN_IN_FOCUSED_WINDOW
通常优于JComponent.WHEN_FOCUSED
,但 BasicTreeUI 使用后者。如果您想使用不同的键,则删除 F2 绑定有点棘手,因为它位于父输入映射中:
I suppose F2 works on your tree nodes because you called
JTree#setEditable(true)
.F2 binding is installed in
BasicTreeUI#installKeyboardActions
. You can install your own binding in the usual way:JComponent.WHEN_IN_FOCUSED_WINDOW
is usually preferable overJComponent.WHEN_FOCUSED
but BasicTreeUI uses the latter.If you want to use a different key, it's a bit tricky to remove the F2 binding as it's in the parent input map: