Search code examples
netbeans-platform

Deleting nodes in a explorer view not in a TopComponent


I am using an explorer view (OutlineView) inside a dialog created from a DialogDescriptor. The following is a stripped-down version of my code:

@ActionID(category = "Example", id = "org.example.Test")
@ActionRegistration(displayName = "Test")
@ActionReference(path = "Menu/File", position = 0)
public class SomeAction implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent e) {
    DialogDescriptor dd = new DialogDescriptor(new MyPanel(), "Titel", true, null);
    DialogDisplayer.getDefault().notify(dd);
  }
}

class MyPanel extends JPanel implements ExplorerManager.Provider {
  private final ExplorerManager em;

  public MyPanel() {
    em = new ExplorerManager();
    em.setRootContext(new MyNode());
    add(new OutlineView());
  }

  @Override
  public ExplorerManager getExplorerManager() {
    return em;
  }
}

class MyNode extends AbstractNode {
  public MyNode() { super(Children.LEAF); }

  @Override
  public Action[] getActions(boolean context) {
    return new Action[] { SystemAction.get(DeleteAction.class) };
  }

  @Override
  public boolean canDestroy() {
    return true;
  }

  @Override
  public void destroy() {
    // Never called
  }
}

When the action is invoked, the dialog is displayed and the outline view does show the root node. However, selecting Delete from the node's context menu opens up a confirmation dialog to delete whatever has been selected in the active TopComponent behind the modal dialog. How to I make the Delete system action consider the selection in the dialog instead? I think I need something akin to this

ActionMap map = getActionMap();
map.put("delete", ExplorerUtils.actionDelete(em, true));
associateLookup(ExplorerUptils.createLookup(em, map));

taken from a TopComponent but couldn't quite figure out what goes wrong. Any pointers are thus greatly appreciated.


Solution

  • In the MyPanel constructor you have to add the delete action to the action map of the outline view:

    OutlineView outlineView = new OutlineView();
    DeleteAction delAction = SystemAction.get(DeleteAction.class);
    
    outlineView.getOutline().getActionMap().put(delAction.getActionMapKey(), ExplorerUtils.actionDelete(em,true));
    

    If you also want to enable the Delete key, you have to put the same action map key to the input map of outline view:

    KeyStroke delKey = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
    outlineView.getOutline().getInputMap().put(delKey, delAction.getActionMapKey());