Adding Context Menu Items To Tree Nodes

When the CTree control detects that a popup menu needs to be displayed, it calls the instance of the CTreeNode and asks it for a list of items to display in the context menu. The following are rules or guidelines for how CTreeNode objects should build this array:

The CTree then calls each plug-in, retrieving any additional menu items for the specified CTreeNode object. If there are additional items, the CTree places a separator after the original menu items, then places all of the plug-in items in the popup menu, and then, if the CTreeNode can be put on custom views, puts another separator and the menu items related to custom views.

For a plug-in to respond to the CTree properly in this case, add a class called ConsoleTreeHandler to the plug-in root package. In our example, this would be com.MyPlugin.ConsoleTreeHandler. Add a method called “getContextMenuItemsFor()” to this class. The source code could look something like the following example:

public static Component[] getContextMenuItmsFor(CTreeNode node) {
  // strictly speaking, this check for null should never be
  // necessary
  if (node == null)
    return new Component[0];
  if (node instanceof SomeSpecificTreeNode) {
    JMenuItem theItem = new JMenuItem("Walk");
    JMenuItem anotherItem = new JMenuItem("Don't walk");
    theItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        // take action here.
      }
    }
    return new Component[] { theItem, anotherItem };
  }
  else if (node instanceof SomeOtherTreeNode) {
    // different set of menu items here.
  }
  // and if we're not interested in any other types.
  return new Component[0].
}

Items of interest for this operation: