Search code examples
filejtablelistenerjtree

How to get path from TreeSelectionListener


Here is my problem. I would like to write a primitive MultiRenameTool (the rename part is not important yet). You could browse the directories on the left side (JTree), and when you select one, you could see its content on the right side (JTable - just the files).

snapshot

The problem is, that I can't figure out how to pass the the selected directory to the JTable's list.

I've used the code of Kirill Grouchnikov for the JTree and I slighty modified it.

import java.awt.BorderLayout;
import java.awt.Component;
import java.io.File;
import java.io.FileFilter;
import java.util.*;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

/**
 * @author Kirill Grouchnikov
 */

public class FileTreePanel extends JPanel {

    protected static FileSystemView fsv = FileSystemView.getFileSystemView();
    private JTree tree;
    //At first I was trying this - but it is wrong.
    public static File current;

    private static class FileTreeCellRenderer extends DefaultTreeCellRenderer {

    private Map<String, Icon> iconCache = new HashMap<String, Icon>();
    private Map<File, String> rootNameCache = new HashMap<File, String>();

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        FileTreeNode ftn = (FileTreeNode) value;
        File file = ftn.file;
        String filename = "";
        if (file != null) {
        if (ftn.isFileSystemRoot) {
            filename = this.rootNameCache.get(file);
            if (filename == null) {
            filename = fsv.getSystemDisplayName(file);
            this.rootNameCache.put(file, filename);
            }

        } else {
            filename = file.getName();
        }
        }
        JLabel result = (JLabel) super.getTreeCellRendererComponent(tree, filename, sel, expanded, leaf, row, hasFocus);
        if (file != null) {
        Icon icon = this.iconCache.get(filename);
        if (icon == null) {
            icon = fsv.getSystemIcon(file);
            this.iconCache.put(filename, icon);
        }
        result.setIcon(icon);
        }
        return result;
    }
    }

    private static class FileTreeNode implements TreeNode {

    private File file;
    private File[] children;
    private TreeNode parent;
    private boolean isFileSystemRoot;

    public FileTreeNode(File file, boolean isFileSystemRoot, TreeNode parent) {
        this.file = file;
        this.isFileSystemRoot = isFileSystemRoot;
        this.parent = parent;
        this.children = this.file.listFiles(new FileFilter() {
        //!Modification here - display only the directories
        @Override
        public boolean accept(File file) {
            return file.isDirectory();
        }
        });
        if (this.children == null) {
        this.children = new File[0];
        }
        //obliviously wrong "solution" :(
        current = file;
    }

    public FileTreeNode(File[] children) {
        this.file = null;
        this.parent = null;
        this.children = children;
    }

    @Override
    public Enumeration<?> children() {
        final int elementCount = this.children.length;
        return new Enumeration<File>() {
        int count = 0;

        @Override
        public boolean hasMoreElements() {
            return this.count < elementCount;
        }

        @Override
        public File nextElement() {
            if (this.count < elementCount) {
            return FileTreeNode.this.children[this.count++];
            }
            throw new NoSuchElementException("Nincs több elem.");
        }
        };
    }

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

    @Override
    public TreeNode getChildAt(int childIndex) {
        return new FileTreeNode(this.children[childIndex],
            this.parent == null, this);
    }

    @Override
    public int getChildCount() {
        return this.children.length;
    }

    @Override
    public int getIndex(TreeNode node) {
        FileTreeNode ftn = (FileTreeNode) node;
        for (int i = 0; i < this.children.length; i++) {
        if (ftn.file.equals(this.children[i])) {
            return i;
        }
        }
        return -1;
    }

    @Override
    public TreeNode getParent() {
        return this.parent;
    }

    @Override
    public boolean isLeaf() {
        return (this.getChildCount() == 0);
    }
    }

    public FileTreePanel() {
    super();
    this.setLayout(new BorderLayout());

    File[] roots = File.listRoots();

    FileTreeNode rootTreeNode = new FileTreeNode(roots);
    this.tree = new JTree(rootTreeNode);
    this.tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);


    this.tree.setCellRenderer(new FileTreeCellRenderer());
    this.tree.setRootVisible(true);
    this.tree.addTreeSelectionListener(new JTreeSelectionListener());

    JScrollPane jsp = new JScrollPane(this.tree);
    this.add(jsp, BorderLayout.CENTER);
    }

    private class JTreeSelectionListener implements TreeSelectionListener {

    @Override
    public void valueChanged(TreeSelectionEvent jtsl) {
        TreePath o = jtsl.getPath();
        System.out.println(o);
        System.out.println(current);

        SelectionList.listBuilder(current);
    }
    }
}

The most important part is at the end, at the TreeSelectionEvent. Here somehow I should be able to convert/make/cast a File from the actually selected Directory.

import java.awt.BorderLayout;
import java.awt.Color;
import java.io.File;
import java.io.FileFilter;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class SelectionList extends JPanel {

    private static FilesData data;
    private static JTable table;

    public SelectionList() {
    super();
    data = new FilesData();
    table = new JTable(data);

    table.setFillsViewportHeight(true);
    table.setShowGrid(true);
    table.setGridColor(Color.BLACK);

    JScrollPane jsp = new JScrollPane(table);
    this.add(jsp, BorderLayout.CENTER);

    }

    public static void listBuilder(final File f) {
    data.files.clear();
    File[] fs = f.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
        return file.isFile();
        }
    });
    if (fs != null) {
        for (File m : fs) {
        Files ujFile = new Files(m, m.isHidden(), Menu.checkAll.getState());
        if (!m.isHidden() || Menu.hiddenFilesVisibility.getState()) {
            data.files.add(ujFile);
        }
        }
    }
    table.repaint();
    }
}

It is interesting because of the listBuilder function. I think it is enough information, but if you need my other classes too, I will upload it. I appreciate any help! Thank you all in avance. Anyone? :(


Solution

  • The following snippet shows how you may get the file from the path inside valueChanged:

    public void valueChanged(TreeSelectionEvent jtsl) {
    
        TreePath path = jtsl.getPath();
        FileTreeNode filenode = (FileTreeNode) path.getLastPathComponent();
        File file = filenode.file;
    
        ...
    
    }