Solved

Swing tree node context menu

Posted on 2010-11-08
6
1,034 Views
Last Modified: 2012-05-10
I have TreeNodes in a JTree.  I would like to add a popup context menu to each of the nodes.  This will popup when I right click on a node.  I do not intend to insert/delete nodes.  The context menu would have options such as Mark for Upload.  Can this context menu be added to a regular TreeNode or does it require DefaultMutableTreeNode?
0
Comment
Question by:mock5c
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 34092799
Remark that TreeNode is no class but an interface.

>> Can this context menu be added to a regular TreeNode
Yes.

>> or does it require DefaultMutableTreeNode?
No. But it can make your life easier to use DefaultMutableTreeNode and in that sense I would recommended it.

0
 

Author Comment

by:mock5c
ID: 34092924
In that case, is it straightforward to cast TreeNode to DefaultMutableTreeNode?  TreeNodes are used heavily in the code.
0
 
LVL 37

Accepted Solution

by:
zzynx earned 125 total points
ID: 34093044
>> In that case, is it straightforward to cast TreeNode to DefaultMutableTreeNode?
Don't understand.
Make sure you have DefaultMutableTreeNode's in your tree (by extending your MyTreeNode from DefaultMutableTreeNode) and you're done. No need to cast.
0
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 
LVL 1

Expert Comment

by:GenroseSusai
ID: 34093791
Tree with popup
___________________

public class TreeWithPopup extends JPanel {
   
    DefaultMutableTreeNode root, node1, node2, node3;
   
    public TreeWithPopup() {
        MyJTree tree;
        root = new DefaultMutableTreeNode("root", true);
        node1 = new DefaultMutableTreeNode("node 1", true);
        node2 = new DefaultMutableTreeNode("node 2" , true);
        node3 = new DefaultMutableTreeNode("node 3", true);
        root.add(node1);
        node1.add(node2);
        root.add(node3);
        setLayout(new BorderLayout());
        tree = new MyJTree(root);
        add(new JScrollPane((JTree)tree),"Center");
    }
   
    public Dimension getPreferredSize(){
        return new Dimension(300, 300);
    }
   
    public static void main(String s[]){
        JFrame frame = new JFrame("Tree With Popup");
        TreeWithPopup panel = new TreeWithPopup();
       
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.setForeground(Color.black);
        frame.setBackground(Color.lightGray);
        frame.getContentPane().add(panel,"Center");
       
        frame.setSize(panel.getPreferredSize());
        frame.setVisible(true);
        frame.addWindowListener(new WindowCloser());
    }
}

class WindowCloser extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
        Window win = e.getWindow();
        win.setVisible(false);
        System.exit(0);
    }
}

class MyJTree extends JTree implements ActionListener{
    JPopupMenu popup;
    JMenuItem mi;
   
    MyJTree(DefaultMutableTreeNode dmtn) {
        super(dmtn);
        // define the popup
        popup = new JPopupMenu();
        mi = new JMenuItem("Insert a children");
        mi.addActionListener(this);
        mi.setActionCommand("insert");
        popup.add(mi);
        mi = new JMenuItem("Remove this node");
        mi.addActionListener(this);
        mi.setActionCommand("remove");
        popup.add(mi);
        popup.setOpaque(true);
        popup.setLightWeightPopupEnabled(true);
       
        addMouseListener(
                new MouseAdapter() {
            public void mouseReleased( MouseEvent e ) {
                if ( e.isPopupTrigger()) {
                    popup.show( (JComponent)e.getSource(), e.getX(), e.getY() );
                }
            }
        }
        );
       
    }
    public void actionPerformed(ActionEvent ae) {
        DefaultMutableTreeNode dmtn, node;
       
        TreePath path = this.getSelectionPath();
        dmtn = (DefaultMutableTreeNode) path.getLastPathComponent();
        if (ae.getActionCommand().equals("insert")) {
            node = new DefaultMutableTreeNode("children");
            dmtn.add(node);
            // thanks to Yong Zhang for the tip for refreshing the tree structure.
            ((DefaultTreeModel )this.getModel()).nodeStructureChanged((TreeNode)dmtn);
        }
        if (ae.getActionCommand().equals("remove")) {
            node = (DefaultMutableTreeNode)dmtn.getParent();
            // Bug fix by essam
            int nodeIndex=node.getIndex(dmtn); // declare an integer to hold the selected nodes index
            dmtn.removeAllChildren();          // remove any children of selected node
            node.remove(nodeIndex);            // remove the selected node, retain its siblings
            ((DefaultTreeModel )this.getModel()).nodeStructureChanged((TreeNode)dmtn);       }
    }
}
0
 

Author Comment

by:mock5c
ID: 34097730
>> In that case, is it straightforward to cast TreeNode to DefaultMutableTreeNode?
>Don't understand.
>Make sure you have DefaultMutableTreeNode's in your tree (by extending your MyTreeNode from >DefaultMutableTreeNode) and you're done. No need to cast.

I have a class MyTreeNode implements TreeNode.  Should I just change that to MyTreeNode extends DefaultMutableTreeNode and remove the implementation of the TreeNode functions that I don't need/use?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 34102937
>> I have a class MyTreeNode implements TreeNode.  
>> Should I just change that to MyTreeNode extends DefaultMutableTreeNode and remove the implementation of the TreeNode functions that I don't need/use?
Indeed.
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

627 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question