1

The idea is quite simple: I have a JTree consisting of different subclasses of TreeNode.

The problem: How do I allow the user to select only nodes of type XyNode?

I have thought of just adding a TreeSelectionListener and deselecting any "wrong" nodes the user might select, but it seems quick & dirty.

Writing my own TreeSelectionModel came to mind, but the interface doesnt seem to be meant for the job.

Anyone got experience or a good solution for this?

4

2 回答 2

2

弄清楚了。TreeSelectionModel是正确的地方。

UI 调用setSelectedPaths(TreePath[] paths)addSelectedPaths(TreePath[] paths)TreeSelectionModel用户单击时将这些方法的返回值设置为选择。

只需扩展DefaultTreeSelectionModel和覆盖两个方法,例如:

public TreePath[] setSelected(TreePath[] paths) {
    super(getValidPaths(paths));
}

public TreePath[] getValidPaths(TreePath[] paths) ...

您可以添加任何类型的检查,并且可以分别处理 add(Ctrl-Click) 和 set(normal Click)。

于 2013-07-29T15:12:21.187 回答
0

我以前看过这个建议:

“不确定这是最佳实践,但也许您可以在要验证的组件上放置一个 FocusListener ......在调用事件时调用您的验证,然后如果您不希望焦点成为焦点,则使用该事件因为验证失败而移动?”

阻止 JTree 选择更改发生的最佳方法是什么?

于 2013-07-29T14:38:24.720 回答