SSISO Community

시소당

isLeaf()

자바  파일  검색기인데요

제가  파일  탐색기를  스윙으로  짰는데...

왼쪽은  파일  트리구요  오른쪽은  파일  테이블이에요..

음...  문제점이  있어서  수정좀  부탁드려요  아님  도움말이라두요  ㅜㅜ

첫번째..  스필트로  패널을  구분해  놨는데  양쪽  다에  어떻게  스크롤바를  넣을지..

두번째..  트리를  선택하면  어떻게  테이블에서  선택된  트리의  디렉토리  내용을  보여줄지;;

-----------<소스입니다>-----------

import  java.awt.*;
import  javax.swing.*;
import  javax.swing.table.*;
import  javax.swing.event.*;
import  javax.swing.tree.*;
import  java.io.File;
import  java.util.Date;
import  javax.accessibility.*;
import  java.beans.*;
import  javax.swing.*;
import  javax.swing.text.*;


public  class  JSplitPaneExample  extends  JPanel
{
public  static  void  main(String[]  args)
{
File  root;
root  =  new  File("c://");
//  오브젝트  생성
FileTreeModel  tree_model  =  new  FileTreeModel(root);
FileTableModel  table_model  =  new  FileTableModel(root);
//  트리  생성
JTree  tree  =  new  JTree();
tree.setModel(tree_model);
JTable  table  =  new  JTable(table_model);
//  트리가  클경우  스크롤바  생성
JFrame  frame  =  new  JFrame("JSplitPane");
JSplitPaneExample  panel  =  new  JSplitPaneExample(tree,  table);
frame.getContentPane().add(new  JScrollPane(panel),BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public  JSplitPaneExample(JTree  tree,  JTable  table)
{
JSplitPane  split  =  new  JSplitPane();  //  JSplitPane  객체  생성
split.setLeftComponent(tree);//  분리자  좌측에  컴포넌트  추가
split.setRightComponent(table);  //  분리자  우측에  컴포넌트  추가
split.setOrientation(JSplitPane.HORIZONTAL_SPLIT);  //  컴포넌트  배치  방향  설정
split.setOneTouchExpandable(true);
split.setDividerLocation(300);
split.setDividerSize(10);
split.setPreferredSize(new  Dimension(600,  500));
this.add(split);
}
}

class  FileTableModel  extends  AbstractTableModel  {
protected  File  dir;
protected  String[]  filenames;

protected  String[]  columnNames  =  new  String[]  {
"name",  "size",  "last  modified",  "directory?",  "readable?",  "writable?"
};

protected  Class[]  columnClasses  =  new  Class[]  {
String.class,  Long.class,  Date.class,
Boolean.class,  Boolean.class,  Boolean.class
};

//  선택된디렉토리의  정보를  표시
public  FileTableModel(File  dir)  {
this.dir  =  dir;
this.filenames  =  dir.list();  //  디렉토리의  파일을  저장
}

public  int  getColumnCount()  {  return  6;  }  //  파일이나  디렉토리를  표시하는  열의  갯수반환
public  int  getRowCount()  {  return  filenames.length;  }  //  디렉토리안의  파일  양

//  각열의  정보표시
public  String  getColumnName(int  col)  {  return  columnNames[col];  }
public  Class  getColumnClass(int  col)  {  return  columnClasses[col];  }

//  각  튜플의  표시해야할  값들을  반환
public  Object  getValueAt(int  row,  int  col)  {
File  f  =  new  File(dir,  filenames[row]);
switch(col)  {
case  0:  return  filenames[row];
case  1:  return  new  Long(f.length());
case  2:  return  new  Date(f.lastModified());
case  3:  return  f.isDirectory()  ?  Boolean.TRUE  :  Boolean.FALSE;
case  4:  return  f.canRead()  ?  Boolean.TRUE  :  Boolean.FALSE;
case  5:  return  f.canWrite()  ?  Boolean.TRUE  :  Boolean.FALSE;
default:  return  null;
}
}
}


class  FileTreeModel  implements  TreeModel  {
//  처음  생성시  루트위치  결정
protected  File  root;
public  FileTreeModel(File  root)  {  this.root  =  root;  }

//  트리의  루트  객체를  반환
public  Object  getRoot()  {  return  root;  }

//  트리의  하위디렉토리가없는  파일  디렉토리인지  판별
public  boolean  isLeaf(Object  node)  {  return  ((File)node).isFile();  }

//  하위노드의  값을  반환
public  int  getChildCount(Object  parent)  {
String[]  children  =  ((File)parent).list();
if  (children  ==  null)  return  0;
return  children.length;
}

//  트리에  각노드를  붙여넣음
//  트리의  모든  파일  노드를  반환
//  File.toString()가  불릴때마다  하위  노드를  표시.
public  Object  getChild(Object  parent,  int  index)  {
String[]  children  =  ((File)parent).list();
if  ((children  ==  null)  ||  (index  >=  children.length))  return  null;
return  new  File((File)  parent,  children[index]);
}

//  어떤  상위노드에  속하는  하위  노드인지  판별
public  int  getIndexOfChild(Object  parent,  Object  child)  {
String[]  children  =  ((File)parent).list();
if  (children  ==  null)  return  -1;
String  childname  =  ((File)child).getName();
for(int  i  =  0;  i  <  children.length;  i++)  {
if  (childname.equals(children[i]))  return  i;
}
return  -1;
}

//  트리를  변환시  불리는  함수
public  void  valueForPathChanged(TreePath  path,  Object  newvalue)  {}

//  노드를  삽입,  제거하는  함수
public  void  addTreeModelListener(TreeModelListener  l)  {}
public  void  removeTreeModelListener(TreeModelListener  l)  {}
}

--------------------------------------------------------------------------------------

  JScrollPane과  addTreeSelectionListener를  이용합니다.


아래  소스를  참고하시기  바랍니다.

1.  scroll이  표시되도록  하는  부분은  아래  빨간  부분을  살펴보시기  바랍니다.

2.  tree를  선택할  때,  오른쪽에  해당  디렉토리의  내용을  보여주게  하는  부분은  아래  파란  부분을  살펴보시기  바랍니다.

import  java.io.*;
import  java.util.*;
import  java.awt.*;
import  javax.swing.*;
import  javax.swing.event.*;
import  javax.swing.table.*;
import  javax.swing.tree.*;

  

public  class  JSplitPaneExample  extends  JPanel  {
    public  static  void  main(String[]  args)  {
        File  root;
        root  =  new  File("c://");

  

        //  오브젝트  생성
        FileTreeModel  tree_model  =  new  FileTreeModel(root);
        FileTableModel  table_model  =  new  FileTableModel(root);

        final  JTable  table  =  new  JTable(table_model);  /*  위치  이동,  final  선언  */

  

        //  트리  생성
        JTree  tree  =  new  JTree();
        tree.addTreeSelectionListener(new  TreeSelectionListener()  {
            public  void  valueChanged(TreeSelectionEvent  ev)  {
                File  file  =  (File)  ev.getPath().getLastPathComponent();

                if  (file.isDirectory())  {
                    table.setModel(new  FileTableModel(file));
                }
            }
        });
        tree.setModel(tree_model);

  

        //  트리가  클경우  스크롤바  생성
        JFrame  frame  =  new  JFrame("JSplitPane");
        JSplitPaneExample  panel  =  new  JSplitPaneExample(tree,  table);
        frame.getContentPane().add(panel,  BorderLayout.CENTER);  /*  JScrollPane  필요없음  */
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

  

    public  JSplitPaneExample(JTree  tree,  JTable  table)  {
        setLayout(new  BorderLayout());  /*  추가  */

        JSplitPane  split  =  new  JSplitPane();  //  JSplitPane  객체  생성
        split.setLeftComponent(new  JScrollPane(tree));  //  분리자  좌측에  컴포넌트  추가  /*  JScrollPane  추가  */
        split.setRightComponent(new  JScrollPane(table));  //  분리자  우측에  컴포넌트  추가  /*  JScrollPane  추가  */
        split.setOrientation(JSplitPane.HORIZONTAL_SPLIT);  //  컴포넌트  배치  방향  설정
        split.setOneTouchExpandable(true);
        split.setDividerLocation(300);
        split.setDividerSize(10);
        split.setPreferredSize(new  Dimension(600,  500));

        this.add(split,  BorderLayout.CENTER);  /*  수정  */
    }
}

  

class  FileTableModel  extends  AbstractTableModel  {
    protected  File  dir;
    protected  String[]  filenames;

    protected  String[]  columnNames  =  new  String[]  {
            "name",  "size",  "last  modified",  "directory?",  "readable?",  "writable?"
    };

  

    protected  Class[]  columnClasses  =  new  Class[]  {
            String.class,  Long.class,  Date.class,
            Boolean.class,  Boolean.class,  Boolean.class
    };

  

    //  선택된디렉토리의  정보를  표시
    public  FileTableModel(File  dir)  {
        this.dir  =  dir;
        this.filenames  =  dir.list();  //  디렉토리의  파일을  저장
    }

  

    public  int  getColumnCount()  {
        return  6;
    }  //  파일이나  디렉토리를  표시하는  열의  갯수반환

  

    public  int  getRowCount()  {
        return  filenames.length;
    }  //  디렉토리안의  파일  양

  

    //  각열의  정보표시
    public  String  getColumnName(int  col)  {
        return  columnNames[col];
    }

  

    public  Class  getColumnClass(int  col)  {
        return  columnClasses[col];
    }

  

    //  각  튜플의  표시해야할  값들을  반환
    public  Object  getValueAt(int  row,  int  col)  {
        File  f  =  new  File(dir,  filenames[row]);
        switch  (col)  {
            case  0:
                return  filenames[row];
            case  1:
                return  new  Long(f.length());
            case  2:
                return  new  Date(f.lastModified());
            case  3:
                return  f.isDirectory()  ?  Boolean.TRUE  :  Boolean.FALSE;
            case  4:
                return  f.canRead()  ?  Boolean.TRUE  :  Boolean.FALSE;
            case  5:
                return  f.canWrite()  ?  Boolean.TRUE  :  Boolean.FALSE;
            default:
                return  null;
        }
    }
}

  

class  FileTreeModel
        implements  TreeModel  {
    //  처음  생성시  루트위치  결정
    protected  File  root;


    public  FileTreeModel(File  root)  {
        this.root  =  root;
    }

  

    //  트리의  루트  객체를  반환
    public  Object  getRoot()  {
        return  root;
    }

  

    //  트리의  하위디렉토리가없는  파일  디렉토리인지  판별
    public  boolean  isLeaf(Object  node)  {
        return  ((File)  node).isFile();
    }

  

    //  하위노드의  값을  반환
    public  int  getChildCount(Object  parent)  {
        String[]  children  =  ((File)  parent).list();
        if  (children  ==  null)
            return  0;
        return  children.length;
    }

  

    //  트리에  각노드를  붙여넣음
    //  트리의  모든  파일  노드를  반환
    //  File.toString()가  불릴때마다  하위  노드를  표시.
    public  Object  getChild(Object  parent,  int  index)  {
        String[]  children  =  ((File)  parent).list();
        if  ((children  ==  null)  ||  (index  >=  children.length))
            return  null;
        return  new  File((File)  parent,  children[index]);
    }

  

    //  어떤  상위노드에  속하는  하위  노드인지  판별
    public  int  getIndexOfChild(Object  parent,  Object  child)  {
        String[]  children  =  ((File)  parent).list();
        if  (children  ==  null)
            return  -1;
        String  childname  =  ((File)  child).getName();
        for  (int  i  =  0;  i  <  children.length;  i++)  {
            if  (childname.equals(children[i]))
                return  i;
        }
        return  -1;
    }

  

    //  트리를  변환시  불리는  함수
    public  void  valueForPathChanged(TreePath  path,  Object  newvalue)  {}  

    //  노드를  삽입,  제거하는  함수
    public  void  addTreeModelListener(TreeModelListener  l)  {}  

    public  void  removeTreeModelListener(TreeModelListener  l)  {}
}

1073 view

4.0 stars