下面列出了javax.swing.tree.DefaultMutableTreeNode#getParent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public DefaultMutableTreeNode getSelectedServerNode() {
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) databaseTree.getLastSelectedPathComponent();
if (treeNode != null) {
Object userObject = treeNode.getUserObject();
if (userObject instanceof MongoCollection) {
return (DefaultMutableTreeNode) treeNode.getParent().getParent();
}
if (userObject instanceof Database) {
return (DefaultMutableTreeNode) treeNode.getParent();
}
if (userObject instanceof DatabaseServer) {
return treeNode;
}
}
return null;
}
@Test
public void testCreatePackagesTree() throws Exception {
//given
TreeSet<String> packages = new TreeSet<>(Arrays.asList("a", "a.b", "c", "c.d"));
HashMap<ClassLikeFilter.Clazz, DefaultMutableTreeNode> map = new HashMap<>();
final DefaultMutableTreeNode root = new DefaultMutableTreeNode(new ClassLikeFilter.Clazz("root"));
//when
filter.createPackagesTree(packages, map, root);
//then
assertEquals(map.size(), 4);
assertTrue(map.containsKey(new ClassLikeFilter.Clazz("a")));
assertTrue(map.containsKey(new ClassLikeFilter.Clazz("a.b")));
assertTrue(map.containsKey(new ClassLikeFilter.Clazz("c")));
assertTrue(map.containsKey(new ClassLikeFilter.Clazz("c.d")));
final DefaultMutableTreeNode child = map.get(new ClassLikeFilter.Clazz("a.b"));
final DefaultMutableTreeNode parent = map.get(new ClassLikeFilter.Clazz("a"));
System.out.println(parent);
final TreeNode parent1 = child.getParent();
assertEquals(parent1, parent);
}
/**
* Removes the selected module in the tvProcessingList from the list
*/
private void removeModule() {
DefaultMutableTreeNode selected = getSelectedItem(tvProcessing);
if (selected == null)
return;
if (selected instanceof DPPModuleTreeNode) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
if (parent instanceof DPPMSLevelTreeNode && ((DPPMSLevelTreeNode) parent).isEnabled()) {
parent.remove(selected);
logger.finest("Removed module " + ((DPPModuleTreeNode) selected).getModule().getName()
+ " from processing list.");
}
} else {
logger.finest("Cannot remove item " + selected.toString() + " from processing list.");
}
((DefaultTreeModel) tvProcessing.getModel()).reload();
expandAllNodes(tvProcessing);
}
private void updateNode(Object arg) {
UpdateElementEvent event = (UpdateElementEvent) arg;
if(event.getElement() instanceof GScreen){
//This function update the position in the tree
//but Screens never needs such of feature.
return;
}
int i = this.getIndex(event.getElement());
DefaultMutableTreeNode node = searchNode(event.getElement());
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
parent.insert(node, i);
jTree2.updateUI();
}
/**
* Create the PopupMenu actions correlating to a specific tree node.
*
* @param aNode - the node
* @param aMenu - the menu to add the actions to
* @param aRecursive - recursive
*/
private void initializeActionsFor(final DefaultMutableTreeNode aNode,
JPopupMenu aMenu, boolean aRecursive) {
Object theUserObject = aNode.getUserObject();
if (!aRecursive) {
JMenuItem theExpandAllItem = new JMenuItem();
theExpandAllItem.setText(getResourceHelper().getFormattedText(
ERDesignerBundle.EXPANDALL));
theExpandAllItem.addActionListener(e -> expandOrCollapseAllChildrenOfNode(new TreePath(aNode
.getPath()), true));
aMenu.add(theExpandAllItem);
JMenuItem theCollapseAllItem = new JMenuItem();
theCollapseAllItem.setText(getResourceHelper().getFormattedText(
ERDesignerBundle.COLLAPSEALL));
theCollapseAllItem.addActionListener(e -> expandOrCollapseAllChildrenOfNode(new TreePath(aNode
.getPath()), false));
aMenu.add(theCollapseAllItem);
aMenu.addSeparator();
}
List<ModelItem> theItemList = new ArrayList<>();
if (theUserObject instanceof ModelItem) {
theItemList.add((ModelItem) theUserObject);
ContextMenuFactory.addActionsToMenu(ERDesignerComponent.getDefault().getEditor(), aMenu, theItemList);
}
if (aNode.getParent() != null) {
initializeActionsFor((DefaultMutableTreeNode) aNode.getParent(),
aMenu, true);
}
}
private void setSelected(final DefaultMutableTreeNode aRootNode, final Boolean isSelected, final boolean aRecursiveSelection) {
//change the direct selection-state of the appropriate leaf node
visitAll(aRootNode, (aValue, aNode) -> {
if (aRecursiveSelection || aValue.equals(aRootNode.getUserObject())) {
if (aValue instanceof SelectableWrapper) {
SelectableWrapper theWrapper = (SelectableWrapper) aValue;
if (isSelected == null) {
theWrapper.invertSelection();
} else {
theWrapper.setSelected(isSelected);
}
return true;
}
return false;
}
return !aRecursiveSelection;
});
//check if the selection state of main nodes is affected indirectly by
//changing selection state of leaf nodes
if (aRootNode.isLeaf() && aRootNode.getUserObject() instanceof SelectableWrapper && ((SelectableWrapper) aRootNode.getUserObject()).getValue() instanceof TableEntry) {
boolean allSelected = true;
DefaultMutableTreeNode theMainNode = (DefaultMutableTreeNode) aRootNode.getParent();
for (int i = 0; (allSelected && (i < theMainNode.getChildCount())); i++) {
allSelected &= (((SelectableWrapper) (((DefaultMutableTreeNode) theMainNode.getChildAt(i)).getUserObject())).isSelected());
}
SelectableWrapper theMainWrapper = (SelectableWrapper) theMainNode.getUserObject();
if (theMainWrapper.isSelected() != allSelected) {
setSelected(theMainNode, allSelected, false);
}
}
}
public DefaultMutableTreeNode getRemainingExpression(PsiExpression expressionToBeRemoved) {
DefaultMutableTreeNode newRoot = new DefaultMutableTreeNode();
processExpression(newRoot, completeExpression);
DefaultMutableTreeNode leaf = newRoot.getFirstLeaf();
while (leaf != null) {
PsiExpression expression = (PsiExpression) leaf.getUserObject();
if (expression.equals(expressionToBeRemoved)) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) leaf.getParent();
if (parent != null) {
DefaultMutableTreeNode grandParent = (DefaultMutableTreeNode) parent.getParent();
DefaultMutableTreeNode sibling = null;
if (leaf.getNextSibling() != null) {
sibling = leaf.getNextSibling();
} else if (leaf.getPreviousSibling() != null) {
sibling = leaf.getPreviousSibling();
}
if (grandParent != null) {
int parentIndex = grandParent.getIndex(parent);
grandParent.remove(parent);
grandParent.insert(sibling, parentIndex);
} else {
newRoot = sibling;
}
} else {
newRoot = null;
}
break;
}
leaf = leaf.getNextLeaf();
}
return newRoot;
}
@javax.annotation.Nullable
private LibraryOrderEntry getSelectedLibrary() {
final AbstractProjectViewPane viewPane = getCurrentProjectViewPane();
DefaultMutableTreeNode node = viewPane != null ? viewPane.getSelectedNode() : null;
if (node == null) return null;
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
if (parent == null) return null;
Object userObject = parent.getUserObject();
if (userObject instanceof LibraryGroupNode) {
userObject = node.getUserObject();
if (userObject instanceof NamedLibraryElementNode) {
NamedLibraryElement element = ((NamedLibraryElementNode)userObject).getValue();
OrderEntry orderEntry = element.getOrderEntry();
return orderEntry instanceof LibraryOrderEntry ? (LibraryOrderEntry)orderEntry : null;
}
PsiDirectory directory = ((PsiDirectoryNode)userObject).getValue();
VirtualFile virtualFile = directory.getVirtualFile();
Module module = (Module)((AbstractTreeNode)((DefaultMutableTreeNode)parent.getParent()).getUserObject()).getValue();
if (module == null) return null;
ModuleFileIndex index = ModuleRootManager.getInstance(module).getFileIndex();
OrderEntry entry = index.getOrderEntryForFile(virtualFile);
if (entry instanceof LibraryOrderEntry) {
return (LibraryOrderEntry)entry;
}
}
return null;
}
/**
* Deletes the selected node from the tree and removes the corresponding entry from the report.
* @param evt
*/
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
selected = (DefaultMutableTreeNode) reportTree.getLastSelectedPathComponent();
if (selected == null) {
//Nothing is selected
return;
}
//If it's a host
if (selected.getPath().length == 2) {
String hostname = selected.toString();
int toDelete = this.getIndexOfHost(hostname);
if (toDelete == -1) {
return;
}
report.getReports().remove(toDelete);
} else if (selected.getPath().length == 3) { //If it's a rule
String host = selected.getParent().toString();
String rule = selected.toString();
int hostNum = this.getIndexOfHost(host);
int ruleNum = this.getIndexOfRule(hostNum, rule);
if (hostNum == -1 || ruleNum == -1) {
return;
}
report.getReports().get(hostNum).getMatchedRules().remove(ruleNum);
}
MutableTreeNode parent = (MutableTreeNode) selected.getParent();
int index = parent.getIndex(selected);
parent.remove(selected);
model.nodesWereRemoved(parent, new int[]{index}, new Object[]{selected});
reportTree.setModel(model);
}
@Override
public final void dragGestureRecognized(final DragGestureEvent dge) {
// final TreePath path = tree.getSelectionPath();
final TreePath path = tree.getPathForLocation(dge.getDragOrigin().x, dge.getDragOrigin().y);
if (path != null) {
draggedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
draggedNodeParent = (DefaultMutableTreeNode) draggedNode.getParent();
if (drawImage) {
final Rectangle pathBounds = tree.getPathBounds(path); // getpathbounds of selectionpath
final JComponent lbl =
(JComponent) tree.getCellRenderer().getTreeCellRendererComponent(tree, draggedNode,
false, tree.isExpanded(path),
((DefaultTreeModel) tree.getModel()).isLeaf(path.getLastPathComponent()), 0, false);// returning
// the
// label
lbl.setBounds(pathBounds);// setting bounds to lbl
image =
new BufferedImage(lbl.getWidth(), lbl.getHeight(),
java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE);// buffered image reference passing
// the label's ht and width
final Graphics2D graphics = image.createGraphics();// creating the graphics for buffered
// image
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); // Sets
// the
// Composite
// for the
// Graphics2D
// context
lbl.setOpaque(false);
lbl.paint(graphics); // painting the graphics to label
graphics.dispose();
}
dragSource.startDrag(dge, DragSource.DefaultMoveNoDrop, image, new Point(0, 0),
new TransferableNode(draggedNode), this);
}
}
@Nonnull
private List<DefaultMutableTreeNode> getPresentationForCommits(@Nonnull final Project project,
@Nonnull List<? extends VcsFullCommitDetails> commits,
int commitsNum) {
Function<VcsFullCommitDetails, DefaultMutableTreeNode> commitToNode = new Function<VcsFullCommitDetails, DefaultMutableTreeNode>() {
@Override
public DefaultMutableTreeNode fun(VcsFullCommitDetails commit) {
return new CommitNode(project, commit);
}
};
List<DefaultMutableTreeNode> childrenToShown = new ArrayList<DefaultMutableTreeNode>();
for (int i = 0; i < commits.size(); ++i) {
if (i >= commitsNum) {
final VcsLinkedTextComponent moreCommitsLink = new VcsLinkedTextComponent("<a href='loadMore'>...</a>", new VcsLinkListener() {
@Override
public void hyperlinkActivated(@Nonnull DefaultMutableTreeNode sourceNode, @Nonnull MouseEvent event) {
TreeNode parent = sourceNode.getParent();
if (parent instanceof RepositoryNode) {
addMoreCommits((RepositoryNode)parent);
}
}
});
childrenToShown.add(new TextWithLinkNode(moreCommitsLink));
break;
}
childrenToShown.add(commitToNode.fun(commits.get(i)));
}
return childrenToShown;
}
/**
* Recursively create the path string for the given node
*
* @param node The node
* @return The path string
* @see #createPathString(TreePath)
*/
private static String createPathString(DefaultMutableTreeNode node)
{
StringBuilder sb = new StringBuilder();
TreeNode parent = node.getParent();
if (parent != null)
{
if (parent instanceof DefaultMutableTreeNode)
{
DefaultMutableTreeNode parentNode =
(DefaultMutableTreeNode)parent;
sb.append(createPathString(parentNode));
sb.append(".");
}
else
{
logger.warning("Unexpected node type: "+parent.getClass());
}
}
Object userObject = node.getUserObject();
if (userObject != null)
{
if (userObject instanceof NodeEntry)
{
NodeEntry nodeEntry = (NodeEntry)userObject;
sb.append(nodeEntry.getName());
}
else
{
logger.warning(
"Unexpected user object type: "+userObject.getClass());
}
}
return sb.toString();
}
private void reload(@Nullable final DefaultMutableTreeNode rootToReload) {
final DefaultTreeModel treeModel = (DefaultTreeModel)myTree.getModel();
if (rootToReload != null && rootToReload != treeModel.getRoot()) {
final List<TreePath> treePaths = TreeUtil.collectExpandedPaths(myTree, new TreePath(rootToReload.getPath()));
final List<TreePath> selectionPaths = TreeUtil.collectSelectedPaths(myTree, new TreePath(rootToReload.getPath()));
final TreePath path = new TreePath(rootToReload.getPath());
final boolean wasCollapsed = myTree.isCollapsed(path);
final Runnable runnable = new Runnable() {
@Override
public void run() {
if (!isTreeShowing() || rootToReload.getParent() == null) return;
TreeUtil.sort(rootToReload, getNodeComparator());
treeModel.reload(rootToReload);
if (!wasCollapsed) {
myTree.collapsePath(path);
for (TreePath treePath : treePaths) {
myTree.expandPath(treePath);
}
for (TreePath selectionPath : selectionPaths) {
TreeUtil.selectPath(myTree, selectionPath);
}
}
}
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
runnable.run();
}
else {
SwingUtilities.invokeLater(runnable);
}
}
else {
TreeUtil.sort(treeModel, getNodeComparator());
treeModel.reload();
}
}
/**
* Item selected.
*
* @param node the node
* @param userObject the user object
*/
@Override
public void itemSelected(DefaultMutableTreeNode node, Object userObject) {
SelectedSymbol selectedSymbol = SelectedSymbol.getInstance();
// Individual symbol selected
Symbolizer symbolizer = (Symbolizer) userObject;
if (node != null) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
if (parent != null) {
selectedSymbol.setSymbolizer(symbolizer);
}
}
}
/**
*
* @param root
* @return boolean bad leaves were returned
*/
private boolean removeBadLeaves(DefaultMutableTreeNode root) {
// no bad leaves yet
boolean badLeaves = false;
// reference first leaf
DefaultMutableTreeNode leaf = root.getFirstLeaf();
// if leaf is root then its the only node
if (leaf.isRoot())
return false;
int leafCount = root.getLeafCount(); // this get method changes if in for loop so have to define outside of it
for (int i = 0; i < leafCount; i++) {
DefaultMutableTreeNode nextLeaf = leaf.getNextLeaf();
// if it does not start with the text then snip it off its parent
if (!filter.accepts(filterText, leaf.getUserObject().toString())) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) leaf.getParent();
if (parent != null)
parent.remove(leaf);
badLeaves = true;
}
leaf = nextLeaf;
}
return badLeaves;
}
public void expandTreeToDepth(DefaultMutableTreeNode node, int depth, String userId, List<ListOptionSerialized> blankRestrictedTools, List<String> accessAdminNodeIds, boolean onlyAccessNodes, boolean shopping, boolean shoppingPeriodTool, String filterSearch){
projectLogic.addChildrenNodes(node, userId, blankRestrictedTools, onlyAccessNodes, accessAdminNodeIds, shopping, shoppingPeriodTool);
//set expand flag to true so to not look for children again:
((NodeModel) node.getUserObject()).setAddedDirectChildrenFlag(true);
getTree().getTreeState().expandNode(node);
if(depth > 0){
//recursive function stopper:
int newDepth = depth - 1;
//count down backwards since we could be deleting these children nodes
for(int i = node.getChildCount() - 1; i >= 0; i--){
expandTreeToDepth((DefaultMutableTreeNode) node.getChildAt(i), newDepth, userId, blankRestrictedTools, accessAdminNodeIds, onlyAccessNodes, shopping, shoppingPeriodTool, filterSearch);
}
}else{
//make sure all children are collapsed and filter out the ones that need to be filtered
//count down backwards since we could be deleting these children nodes
for(int i = node.getChildCount() - 1; i >= 0; i--){
getTree().getTreeState().collapseNode(node.getChildAt(i));
String nodeTitle = ((NodeModel) ((DefaultMutableTreeNode) node.getChildAt(i)).getUserObject()).getNode().description.toLowerCase();
if(filterSearch != null && !"".equals(filterSearch.trim()) && !nodeTitle.contains(filterSearch.toLowerCase())){
//delete this child:
node.remove(i);
}
}
}
//check if all of the children have been removed (but don't delete root node)
if(node.getParent() != null && node.getChildCount() == 0){
((DefaultMutableTreeNode) node.getParent()).remove(node);
}
}
/**
* Tests if the removal is valid and then removes the path from the constraint
*
* @param e The action event
*/
@Override
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
// If there is nothing seleceted then just do nothing
if (_theFrame.getInfoTreeUI().getInfoTree().isSelectionEmpty()) {
return;
}
// If we're currently synced with a db, give the user the chance to
// cancel operation
if (_theFrame.getMModel().isSynced()) {
int choice = JOptionPane.showConfirmDialog(_theFrame,
"Warning: this sketch is currently synced with a db; continue and break synchronization?",
"Warning!", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if (choice == JOptionPane.CANCEL_OPTION) {
return;
}
}
// Get currently selected object
DefaultMutableTreeNode curSelected = (DefaultMutableTreeNode) _theFrame.getInfoTreeUI().getInfoTree()
.getSelectionPath().getLastPathComponent();
// Selection is a constraint
if (curSelected instanceof ModelPath) {
ModelConstraint<F, GM, M, N, E> curConstraint = (ModelConstraint<F, GM, M, N, E>) curSelected.getParent();
ArrayList<ModelPath<F, GM, M, N, E>> tempPaths = new ArrayList<>();
tempPaths.remove(curSelected);
boolean valid = false;
if (curConstraint instanceof SumConstraint) {
valid = _theFrame.getMModel().isSumConstraint(tempPaths);
// Replace previous path array list
if (valid) {
((SumConstraint<F, GM, M, N, E>) curConstraint).setPaths(tempPaths);
}
} else if (curConstraint instanceof ProductConstraint) {
valid = _theFrame.getMModel().isProductConstraint(tempPaths);
// Replace previous path array list
if (valid) {
((ProductConstraint<F, GM, M, N, E>) curConstraint).setPaths(tempPaths);
}
} else if (curConstraint instanceof CommutativeDiagram) {
valid = _theFrame.getMModel().isCommutativeDiagram(tempPaths);
// Replace previous path array list
if (valid) {
((CommutativeDiagram<F, GM, M, N, E>) curConstraint).setPaths(tempPaths);
}
} else {
JOptionPane.showMessageDialog(_theFrame,
"You don't have a path selected that can be removed. \nPlease select another path and try again.",
"No ModelConstraint Selected", JOptionPane.ERROR_MESSAGE);
return;
}
if (valid) {
ModelConstraint<F, GM, M, N, E> myConst = curConstraint;
// Remove old tree node
myConst.removeFromParent();
_theFrame.getInfoTreeUI().addConstraint(myConst);
// Referesh Tree
_theFrame.getInfoTreeUI().refreshTree(myConst);
_theFrame.getMModel().setDirty();
_theFrame.getMModel().setSynced(false);
} else {
JOptionPane.showMessageDialog(_theFrame,
"Revoming this path would make the constraint invalid.\nPath was not removed",
"Path Not Removed", JOptionPane.ERROR_MESSAGE);
}
}
// Selection is not a constraint
else {
JOptionPane.showMessageDialog(_theFrame,
"You don't have a path selected. \nPlease select a path and try again.",
"No ModelConstraint Selected", JOptionPane.ERROR_MESSAGE);
}
}
/** Removes the item. */
public void removeItem() {
if (symbolTree == null) {
return;
}
TreePath path = symbolTree.getSelectionPath();
if (path == null) {
return;
}
DefaultMutableTreeNode lastNode = (DefaultMutableTreeNode) path.getLastPathComponent();
Object obj = lastNode.getUserObject();
// CHECKSTYLE:OFF
Object oldValueObj = sldWriter.encodeSLD(null, SelectedSymbol.getInstance().getSld());
// CHECKSTYLE:ON
if (obj instanceof NamedLayer) {
SelectedSymbol.getInstance().removeUserNamedLayer((NamedLayer) obj);
removeTreeNode(lastNode);
} else if (obj instanceof UserLayer) {
SelectedSymbol.getInstance().removeUserNamedLayer((UserLayer) obj);
removeTreeNode(lastNode);
} else if (obj instanceof Style) {
SelectedSymbol.getInstance().removeStyle((Style) obj);
removeTreeNode(lastNode);
} else if (obj instanceof FeatureTypeStyle) {
SelectedSymbol.getInstance().removeFeatureTypeStyle((FeatureTypeStyle) obj);
removeTreeNode(lastNode);
} else if (obj instanceof Rule) {
SelectedSymbol.getInstance().removeRule((Rule) obj);
removeTreeNode(lastNode);
} else if (obj instanceof Symbolizer) {
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) lastNode.getParent();
if (parentNode != null) {
if (parentNode.getUserObject() instanceof RasterSymbolizer) {
SelectedSymbol.getInstance()
.removeRasterImageOutline(
(RasterSymbolizer) parentNode.getUserObject());
} else {
SelectedSymbol.getInstance().removeSymbolizer((Symbolizer) obj);
}
removeTreeNode(lastNode);
}
} else {
return;
}
SLDTreeManager.getInstance().rebuildTree((SLDTree) sldTree);
// Re-render the symbol
if (renderList != null) {
for (RenderSymbolInterface render : renderList) {
render.renderSymbol();
}
}
Object newValueObj = sldWriter.encodeSLD(null, SelectedSymbol.getInstance().getSld());
UndoManager.getInstance()
.addUndoEvent(
new UndoEvent(
sldTree.getUndoObject(),
getClass().getName(),
oldValueObj,
newValueObj));
}
public boolean canPerformAction(DNDTree target, DefaultMutableTreeNode dragged_node, int action, Point location) {
/* //debug:
Utils.log2(DnDConstants.ACTION_COPY + " " + DnDConstants.ACTION_COPY_OR_MOVE + " " + DnDConstants.ACTION_LINK + " " + DnDConstants.ACTION_MOVE + " " + DnDConstants.ACTION_NONE + " " + DnDConstants.ACTION_REFERENCE);
Utils.log2("action: " + action);
*/
// prevent drags from non-tree components
if (null == dragged_node) return false;
// Can't drop onto a TemplateTree
if (target instanceof TemplateTree) {
return false;
}
// Can't drag a node that contains a Project!
if (dragged_node.getUserObject() instanceof ProjectThing && ((ProjectThing)dragged_node.getUserObject()).getObject() instanceof Project) {
return false;
}
// Can't drag basic object nodes from a template tree RECONSIDERED, I like it even if it looks inconsistent (but types are types!)
/*
if (dragged_node.getUserObject() instanceof TemplateThing && project.isBasicType(((Thing)dragged_node.getUserObject()).getType())) {
return false;
}
*/
// else, the target has to be not null
TreePath pathTarget = target.getPathForLocation(location.x, location.y);
if (pathTarget == null) {
target.setSelectionPath(null);
return false;
}
/* // debug
if (action == DnDConstants.ACTION_COPY) {
Utils.log("can drop: Action copy");
} else if (action == DnDConstants.ACTION_MOVE) {
Utils.log("can drop: Action move");
} else {
Utils.log("can drop: Unexpected action: " + action);
}
*/
target.setSelectionPath(pathTarget);
DefaultMutableTreeNode parent_node = (DefaultMutableTreeNode)pathTarget.getLastPathComponent();
Object parent_ob = parent_node.getUserObject(); // can be a Thing or an Attribute
Thing child_thing = (Thing)dragged_node.getUserObject();
if (DnDConstants.ACTION_MOVE == action || DnDConstants.ACTION_COPY == action) {
if (parent_ob instanceof ProjectThing) {
ProjectThing parent_thing = (ProjectThing)parent_ob;
// TODO: check if the parent/parent/parent/.../parent of the dragged thing can have such parent as child, and autocreate them (but not for basic things though, or only if there is no confusion possible)
// check if it's allowed to give to this parent such a child:
if (!parent_thing.uniquePathExists(child_thing.getType()) && !parent_thing.canHaveAsChild(child_thing)) {
//Utils.log("Not possible.");
return false;
}
// enable to drop:
// - any of the leafs in the template, including the root, to the project tree
// disable to drop:
// - the root leaf of the project tree
// - the leaf that is going to be dropped into itself or any of its descendants.
if (parent_node == dragged_node.getParent() || dragged_node.isNodeDescendant(parent_node)) {
//Utils.log("preventing dragging onto itself or any of the self children.");
return false;
} else {
return true;
}
}
}
// default:
return false;
}
@Override public void drop(DropTargetDropEvent dtde) {
// System.out.println("drop");
// if (!isWebStart()) {
// try {
// draggingObject = dtde.getTransferable().getTransferData(FLAVOR);
// } catch (Exception ex) {
// rejectDrag(dtde);
// return;
// }
// } else {
// draggingObject = getSelectionPath().getLastPathComponent();
// }
Object draggingObject = getSelectionPath().getLastPathComponent();
Point pt = dtde.getLocation();
TreePath path = getPathForLocation(pt.x, pt.y);
if (Objects.isNull(path) || !(draggingObject instanceof MutableTreeNode)) {
dtde.dropComplete(false);
return;
}
// System.out.println("drop path is " + path);
MutableTreeNode draggingNode = (MutableTreeNode) draggingObject;
DefaultMutableTreeNode targetNode = (DefaultMutableTreeNode) path.getLastPathComponent();
if (targetNode.equals(draggingNode)) {
// Cannot move the node to the node itself
dtde.dropComplete(false);
return;
}
dtde.acceptDrop(DnDConstants.ACTION_MOVE);
DefaultTreeModel model = (DefaultTreeModel) getModel();
model.removeNodeFromParent(draggingNode);
TreeNode parent = targetNode.getParent();
if (parent instanceof MutableTreeNode && targetNode.isLeaf()) {
model.insertNodeInto(draggingNode, (MutableTreeNode) parent, parent.getIndex(targetNode));
} else {
model.insertNodeInto(draggingNode, targetNode, targetNode.getChildCount());
}
dtde.dropComplete(true);
dropTargetNode = null;
draggedNode = null;
repaint();
}