Solved

Developing Java Explorer

Posted on 2001-08-07
6
493 Views
Last Modified: 2008-03-17
===========================================================================================

im trying to build a Java Explorer(a la Windows Explorer). Ths following code goes to some extent. im getting 2 problems :

=> The Folders and Files are not in alphabetic order. how do i get it ??(folders first and then files)
=> im able to expand the tree to only one branch. how can i expand it to 'n' branches ??

plzz somebody help me. :(

killi

===========================================================================================

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

public class JavaExplorer extends JFrame implements MouseListener
 {
   JPanel pnlTop, pnlMain;
   JTextPane txtpane;
   JButton btn;
   JSplitPane split;
   JScrollPane jspTree, jspDisp;
   JTree tree;
   DefaultMutableTreeNode root, branch, branch1;

   File folder = new File("d:/Killi/Java/Swings");

   Container c;

   public JavaExplorer()
    {
      c = getContentPane();
      c.add(pnlTop  = new JPanel(), "North");
      c.add(pnlMain = new JPanel());
      pnlMain.setLayout(new BorderLayout());
      pnlTop.add(btn = new JButton("Click"));

      root = new DefaultMutableTreeNode(folder.getPath());
      createNodes(root);
      JTree tree = new JTree(root);
      tree.putClientProperty("JTree.lineStyle", "Angled");
      pnlMain.add(split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jspTree = new JScrollPane(tree), jspDisp = new JScrollPane(txtpane = new JTextPane())));
      split.setDividerLocation(225);

      setSize(500,300);
      setLocation(100,100);
      setVisible(true);
      setTitle("Java Explorer");

      tree.addMouseListener(this);
      addWindowListener(new WindowAdapter()
       {
          public void windowClosing(WindowEvent we)
           { System.exit(0); }
       });
    }

   public void createNodes(DefaultMutableTreeNode root)
    {
      File[] list = folder.listFiles();

      for(int i=0; i<list.length; i++)
       {
         if(list[i].isFile())
          {
            branch = new DefaultMutableTreeNode(list[i]);
            root.add(branch);
          }

         if(list[i].isDirectory())
          {
            branch = new DefaultMutableTreeNode(list[i]);
            root.add(branch);

            File[] list1 = list[i].listFiles();

            for(int j=0; j<list1.length; j++)
             {
               branch1 = new DefaultMutableTreeNode(list1[j]);
               branch.add(branch1);
             }
          }
       }
    }

   public void mouseEntered(MouseEvent me) {}
   public void mouseExited(MouseEvent me) {}
   public void mousePressed(MouseEvent me) {}
   public void mouseReleased(MouseEvent me) {}
   public void mouseClicked(MouseEvent me)
    {
      JOptionPane.showMessageDialog(null, branch1, "Mouse Cick", JOptionPane.INFORMATION_MESSAGE); // this is just for debugging purpose
    }

   public static void main(String args[])
    { new JavaExplorer(); }
 }

===========================================================================================
0
Comment
Question by:killisrinivas
[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 7

Expert Comment

by:tomboshell
ID: 6363585
For the alphabetical seperation I would say to break to another method after you get your File array.  In the new method create two seperate file arrays.  One would hold all the directoris the other all the files.  Iterate through your main array and seperate the files into the two other arrays, and branch to an alphabetizing method (recursive would be best).  Then when done seperating and alphabetizing, add then to the tree in order.  

I don't know about the expansion of the tree.

But I hope that I helped you think about it.
Tom
0
 
LVL 4

Accepted Solution

by:
sdussinger earned 200 total points
ID: 6366862
I've updated your code to do what you want. The code is as follows:

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

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

public class JavaExplorer extends JFrame implements MouseListener
{
    JPanel pnlTop, pnlMain;
    JTextPane txtpane;
    JButton btn;
    JSplitPane split;
    JScrollPane jspTree, jspDisp;
    JTree tree;
    DefaultMutableTreeNode root, branch, branch1;

    // Get the File for the root directory we're searching through.
    File folder = new File(".");

    Container c;

    public JavaExplorer()
    {
    c = getContentPane();
    c.add(pnlTop  = new JPanel(), "North");
    c.add(pnlMain = new JPanel());
    pnlMain.setLayout(new BorderLayout());
    pnlTop.add(btn = new JButton("Click"));

    // Create the root node for our tree-view from the specified folder
    root = createNodes(folder);

    // Install the root into our tree-view.
    JTree tree = new JTree(root);

    tree.putClientProperty("JTree.lineStyle", "Angled");
    pnlMain.add(split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jspTree = new JScrollPane(tree),
                       jspDisp = new JScrollPane(txtpane = new JTextPane())));
    split.setDividerLocation(225);

    setSize(500,300);
    setLocation(100,100);
    setVisible(true);
    setTitle("Java Explorer");

    tree.addMouseListener(this);
    addWindowListener(new WindowAdapter()
        {
        public void windowClosing(WindowEvent we)
        { System.exit(0); }
        });

    // This function creates a tree node for a given directory in the file
    // system. This node will contain a child node for each directory and
    // file found.
    public DefaultMutableTreeNode createNodes(File folder)
    {
    // Create a sorted set for the directories and the files found
    // in this directory.
    TreeSet fileSet = new TreeSet(), dirSet = new TreeSet ();

    // Create the root node for this directory, and ensure that it looks
    // like a folder in the tree-view.
    DefaultMutableTreeNode root = new DefaultMutableTreeNode (folder);
    root.setAllowsChildren (true);

    // Get all of the files/directories under us.
    File[] list = folder.listFiles();

    // Loop through all of the files and directories.
    for (int i = 0 ; i < list.length ; i++)
        {
        // This is a file. Store it into the sorted list of files
        if (list[i].isFile ())
            fileSet.add (list[i]);
        // This one's a directory. Store it into the sorted list
        // of directories.
        else if (list[i].isDirectory ())
            dirSet.add (list[i]);

        }

    // Get an iterator over the list of directories.
    Iterator iter = dirSet.iterator ();

    // For each child directory...
    while (iter.hasNext ())
        {
        // Get the directory from the sorted list...
        File f = (File) iter.next ();

        // And recursively call ourselves to create the node
        // for this directory.
        branch = createNodes (f);

        // Add the newly created node as a child of the root.
        root.add (branch);
        }

    // Now lets loop through the list of files.
    iter = fileSet.iterator ();
   
    while (iter.hasNext ())
        {
        // Get the next file in the list...
        File f = (File) iter.next ();

        // Create a new node for this file...
        branch = new DefaultMutableTreeNode (f);

        // Add it to the current root node.
        root.add (branch);
        }

    // All done. Return the newly created root node.
    return (root);
    }

    public void mouseEntered(MouseEvent me) {}
    public void mouseExited(MouseEvent me) {}
    public void mousePressed(MouseEvent me) {}
    public void mouseReleased(MouseEvent me) {}
    public void mouseClicked(MouseEvent me)
    {
    JOptionPane.showMessageDialog(null, branch1, "Mouse Cick", JOptionPane.INFORMATION_MESSAGE); // this is just for debugging purpose

    public static void main(String args[])
    { new JavaExplorer(); }
}

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

To solve the sorting problem, I iterated over the list of children of a given directory and put the files and directories into sorted TreeSets.

Once all of the children were sorted I iterated over first the directories and then the files to display them in order.

The problem you were having with only being able to get one level of children is due to the fact that you were not recursing through all of the levels of sub-folders. When you found a sub-folder, you listed its contents, but if the sub-folder had sub-folders, you didn't traverse down. I fixed that by making the createNode() function recursive. Pass it a File instance containing a directory, and it'll create the node representing that directory and all of its subdirectories.

Hopefully this will help.

--Steve
0
 
LVL 4

Expert Comment

by:sdussinger
ID: 6382873
Did this work for you?? If not, drop a line and I'll see if I can help...

--Steve
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:killisrinivas
ID: 6449048
hi steve,

  first i'd like to apologise that i didn't give response to ur ans immediately. actually i got a bit busy and couldn't get time to check EE.

   i ran ur code. it was brilliant. i just have to work a bit more on it to display the contents selected on the left column into the right column(if possible the content of the file and images too). i'll do it. thank u very much for the code.

instead of  File folder = new File("."); if u write as File folder = new File("\"); then root directories will be listed. that was very nice of u.

   right now im working on JTable where i give data into the cells and then the data from the rows r updated into the database. i got a problem in this too. i have posed this q at EE with subject as "JTable to database". i'd appreciate if u could help me out in this too.

regards,
killi
0
 
LVL 4

Expert Comment

by:sdussinger
ID: 6449536
Cool. Glad I could help. Go ahead and close this one out, while I take a look at the other one. I'll help if I can.

--Steve
0
 

Author Comment

by:killisrinivas
ID: 6511523
thank u very much steve. im still working on JTable with database. i'll get to u soon. im a busy bee now-a-days.

killi
0

Featured Post

Secure Your Active Directory - April 20, 2017

Active Directory plays a critical role in your company’s IT infrastructure and keeping it secure in today’s hacker-infested world is a must.
Microsoft published 300+ pages of guidance, but who has the time, money, and resources to implement? Register now to find an easier way.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
eclipse buid path vs tomcat lib path 10 38
pagenation logic how it is working in my code 1 71
printf performancy 11 86
Setup GlassFish 4 35
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

733 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