sdasdadas
sdasdadas

Reputation: 25106

Why does it take two clicks to highlight my JTree?

I have a JTree with a SelectionListener attached. The listener is functioning properly and notifies me correctly whenever I click on a node in the tree.

However, the nodes don't always get highlighted when selected. In fact, it requires two clicks to get the visual "blue-box" on the node to appear.

Why does the following code require two clicks to show a selection?

Creation of the JTree

JTree tree = new JTree();
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setDragEnabled(true);
tree.setDropMode(DropMode.ON);
tree.expandRow(0);
tree.setModel(model.getActiveFilterModel());

Adding the Listener

tree.addTreeSelectionListener(new TreeSelectionListener() {
    @Override
        public void valueChanged(TreeSelectionEvent event) {
            JTree tree = (JTree) event.getSource();
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            if (selectedNode != null) {
                model.setSelectedFilter((Filter) selectedNode.getUserObject());
            }
        }
});

EDIT:

I would like to add that it appears only to happen once I call .setModel on the tree a second time.

Upvotes: 1

Views: 189

Answers (1)

sdasdadas
sdasdadas

Reputation: 25106

The problem was that I was using an Observer pattern and continuously calling for the display (eg. the JTree, to update()). This is not a problem by itself.

However, in my update call I was constantly using tree.setModel(...) when really the underlying model takes care of these changes itself. I switched my code to only call setModel() once and everything functions perfectly now.

Upvotes: 1

Related Questions