Solved

Developing Java Explorer

Posted on 2001-08-07
6
487 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
  • 3
  • 2
6 Comments
 
LVL 7

Expert Comment

by:tomboshell
Comment Utility
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
Comment Utility
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
Comment Utility
Did this work for you?? If not, drop a line and I'll see if I can help...

--Steve
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:killisrinivas
Comment Utility
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
Comment Utility
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
Comment Utility
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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

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 …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
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 the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

763 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now