Java Swing TreeModel implement

Introduction

The following program creates a model for file system and displays a specified directory tree.

import java.io.File;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class Main {
   public static void main(String[] args) {
      JFrame f = new JFrame("java2s.com");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setSize(300, 300);//from  w ww  .  ja va 2  s  .  c  o  m
      FSTreeModel model = new FSTreeModel("C:/");
      JTree tree = new JTree();
      tree.setModel(model);
      JScrollPane jsp = new JScrollPane(tree);
      f.getContentPane().add(jsp);
      f.setVisible(true);
   }
}

class FSTreeModel implements TreeModel {
   File root;

   public FSTreeModel(String path) {
      this.root = new File(path);
   }

   public Object getRoot() {
      return root;
   }

   public Object getChild(Object p, int in) {
      String[] c = ((File) p).list();
      return (c == null) || (in >= c.length) ? null : new File((File) p, c[in]);
   }

   public int getIndexOfChild(Object p, Object c) {
      String[] l = ((File) p).list();
      if (l == null)
         return -1;
      String name = ((File) c).getName();
      for (int i = 0; i < l.length; i++)
         if (name.equals(l[i]))
            return i;
      return -1;
   }

   public int getChildCount(Object p) {
      String[] c = ((File) p).list();
      return c != null ? c.length : 0;
   }

   public boolean isLeaf(Object node) {
      return ((File) node).isFile();
   }

   public void addTreeModelListener(TreeModelListener l) {
   }

   public void removeTreeModelListener(TreeModelListener l) {
   }

   public void valueForPathChanged(TreePath path, Object newvalue) {
   }
}



PreviousNext

Related