Maxwell
Maxwell

Reputation: 303

Disable standard mouse behaviour in a JTree

I have got a JTree and in specific cases I want to switch it to a "no user input mode". In this mode the user should be unable to change the selection of the tree. However the current selection should stay unchanged and it should still be able to change programmatically.

I tried to set tree.setFocusable(false) -> User can still change selection

I build a MouseListener that consumed the click events -> User can still change selection

I tried tree.setSelectionModel(null) -> No selection visible

In principle I could tree.setEnabled(false) but then the tree turns gray and ugly.

Any ideas on how I could prevent the user from changing the selection, or alternatively how I could draw the JTree normally in the disabled state?

Upvotes: 0

Views: 503

Answers (1)

Slauster
Slauster

Reputation: 99

I think I'll do something like that :

    tree.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent arg0) {
            TreePath path = ... // The path of the node you want to be selected 
            tree.setSelectionPath(path);
        }
    });

When selection changes you select again the node you need.

Upvotes: 1

Related Questions