@Override public void keyPressed(KeyEvent e) { TreePath path = myTree.getLeadSelectionPath(); if (path == null) return; final Object lastComponent = path.getLastPathComponent(); if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (lastComponent instanceof ParentNode) return; doOKAction(); e.consume(); } else if (e.getKeyCode() == KeyEvent.VK_INSERT) { if (lastComponent instanceof ElementNode) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode) lastComponent; if (!mySelectedNodes.contains(node)) { if (node.getNextNode() != null) { myTree.setSelectionPath(new TreePath(node.getNextNode().getPath())); } } else { if (node.getNextNode() != null) { myTree.removeSelectionPath(new TreePath(node.getPath())); myTree.setSelectionPath(new TreePath(node.getNextNode().getPath())); myTree.repaint(); } } e.consume(); } } }
private Pair<ElementNode, List<ElementNode>> storeSelection() { List<ElementNode> selectedNodes = new ArrayList<ElementNode>(); TreePath[] paths = myTree.getSelectionPaths(); if (paths != null) { for (TreePath path : paths) { selectedNodes.add((ElementNode) path.getLastPathComponent()); } } TreePath leadSelectionPath = myTree.getLeadSelectionPath(); return Pair.create( leadSelectionPath != null ? (ElementNode) leadSelectionPath.getLastPathComponent() : null, selectedNodes); }