简体   繁体   中英

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 .

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?

Figured it out. TreeSelectionModel was the right place to do it.

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.

Simply extend DefaultTreeSelectionModel and override two methods, for example like this:

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.

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?"

Best way to stop a JTree selection change from happening?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM