Jonas Eicher
Jonas Eicher

Reputation: 1513

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?

Upvotes: 1

Views: 230

Answers (2)

Jonas Eicher
Jonas Eicher

Reputation: 1513

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.

Upvotes: 2

JBuenoJr
JBuenoJr

Reputation: 975

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?

Upvotes: 0

Related Questions