KeyListener (final Tree tree, final JComponent mainComponent) { KeyListener listener = new KeyAdapter() { @Override public void keyPressed(@NotNull KeyEvent e) { if (isToggleEvent(e, mainComponent)) { TreePath treePath = tree.getLeadSelectionPath(); if (treePath == null) return; final Object o = treePath.getLastPathComponent(); if (!(o instanceof CheckedTreeNode firstNode)) return; if (!firstNode.isEnabled()) return; toggleNode(tree, firstNode); boolean checked = firstNode.isChecked(); TreePath[] selectionPaths = tree.getSelectionPaths(); for (int i = 0; selectionPaths != null && i < selectionPaths.length; i++) { final TreePath selectionPath = selectionPaths[i]; final Object o1 = selectionPath.getLastPathComponent(); if (!(o1 instanceof CheckedTreeNode node)) continue; setNodeState(tree, node, checked); } e.consume(); } } }; mainComponent.addKeyListener(listener); return listener; }