JTree How to prevent selection of Tree node

I have a JTree and I dont want to disable nodes.
In certain circumstances I would like to perform the following:

When the user clicks on a particular node (other than the currently selected one),
I want to prevent selection of that node and pop up a warning message.
(The warning message is not the issue)
The tree node selection must not change to the clicked one. The original
selected node must remain selected.
Presumably, I could reselect the originally selected node after closing the popup,
but it wouldn't look so good.

The selection process appears to take place before any mouse events are caught
by the listener.

Who is Participating?
zzynxConnect With a Mentor Software engineerCommented:
>> The original selected node must remain selected.

        theTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {

                if (the currently selected node shouldn't be selected)


to get the selected node:

        TreeNode selected = (TreeNode) theTree.getSelectionPath().getLastPathComponent();
Not sure if you can achieve that, will have a think.
objectsConnect With a Mentor Commented:
You actually should be able to achieve that with a custom TreeSelectionModel.
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

richard_fairallAuthor Commented:
Thanks objects,

  For some reason I have to add the clearSelection call or it floods with events, but it works fine.
  I check both old and new selection paths are valid (presumably means a change in node selection)

  public void valueChanged(TreeSelectionEvent e)
    if (e.getSource() != null)   {
      if (e.getOldLeadSelectionPath() != null && e.getNewLeadSelectionPath() != null)   {
richard_fairallAuthor Commented:
Sorry, so used to objects replying I didn't notice it was zzynx who
responded last. I had already got a custom TreeSelectionModel in situ
before I read the last answer, so I'll split the points.
Thanks both.

zzynxSoftware engineerCommented:
Thank you
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.