Search code examples
fileactionjtreedouble-clicktreenode

Adding actions to DefaultMutableTreeNode


I have created a "FileTree" class which displays a file system via a JTree, and only displays folders and ".xlsx" or ".xls" files. I want to be able to add a double-click action to the DefaultMutableTreeNodes if they are a ".xlsx" or ".xls" file. It doesnt seem possible to be able to add an ActionListener or a MouseListener to a DefaultMutableTreeNode, is there a way I can control the double-click action on these nodes?


Solution

  • I have a solution of sorts, its not the one I was looking for, but it does work.

    I have added a MouseListener to the JTree, and then when the click count is 2, I check the event source is an instanceof the JTree, then call

    Object comp = tree.getLastSelectedPathComponent();
    if (comp instanceof FileTreeNode)
    {
        FileTreeNode ftn = (FileTreeNode) comp;
    File file = ftn.getFile();
    }
    

    and then I can do whatever I want with the file. FileTreeNode is an extension of DefaultMutableTreeNode which contains the file at that node.