[英]How can I limit selection in a JTree to a specific type of node?
The idea is quite simple: I have a JTree
consisting of different subclasses of TreeNode
. 这个想法很简单:我有一个
JTree
它由TreeNode
的不同子类组成。
The problem: How do I allow the user to select only nodes of type XyNode
? 问题:如何允许用户仅选择
XyNode
类型的节点?
I have thought of just adding a TreeSelectionListener
and deselecting any "wrong" nodes the user might select, but it seems quick & dirty. 我曾想过只添加一个
TreeSelectionListener
并取消选择用户可能选择的任何“错误”节点,但它看起来又快又脏。
Writing my own TreeSelectionModel
came to mind, but the interface doesnt seem to be meant for the job. 我想到了编写自己的
TreeSelectionModel
,但是该接口似乎并不适合该工作。
Anyone got experience or a good solution for this? 任何人都有经验或好的解决方案吗?
Figured it out. 弄清楚了。
TreeSelectionModel
was the right place to do it. TreeSelectionModel
是执行此操作的正确位置。
The UI calls setSelectedPaths(TreePath[] paths)
and addSelectedPaths(TreePath[] paths)
in the TreeSelectionModel
when the User clicks, then sets the return values of those methods as the Selection. 当用户单击时,UI会在
TreeSelectionModel
调用setSelectedPaths(TreePath[] paths)
和addSelectedPaths(TreePath[] paths)
,然后将这些方法的返回值设置为Selection。
Simply extend DefaultTreeSelectionModel
and override two methods, for example like this: 只需扩展
DefaultTreeSelectionModel
并覆盖两个方法即可,例如:
public TreePath[] setSelected(TreePath[] paths) {
super(getValidPaths(paths));
}
public TreePath[] getValidPaths(TreePath[] paths) ...
You can add any kind of checks, and you can handle add(Ctrl-Click) and set(normal Click) distinctively. 您可以添加任何种类的检查,并且可以区别地处理add(Ctrl-Click)和set(normal Click)。
I have seen this suggestion before: 我以前看过这个建议:
"Not sure it's best practice, but maybe you could put a FocusListener on the component(s) you want to validate... call your validation when the event is called and then consume then event if you don't want the focus to be moved because the validation fails?" “不确定这是最佳实践,但是也许您可以在要验证的组件上放置一个FocusListener……在调用事件时调用验证,然后如果您不希望将焦点放在事件上,则先消耗事件因为验证失败而感动?”
Best way to stop a JTree selection change from happening? 阻止JTree选择更改发生的最佳方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.