A solution using JavaScript

Java Tutorial: Working with Files and Directories in Java:

Recap & Sorting the Files and Directories
Opening and Closing the Folders
A Solution Using JavaScript

A solution using JavaScript

The only disadvantage with this solution is that every click on a folder requires a trip to the web-server and back again to the browser. Compared to clicking on a folder in for example Windows Explorer the response time is remarkably slower. There is another solution that will speed up the response time, and this involves the use of some JavaScript. Note that the solution presented only works in Internet Explorer.

The idea is that the whole directory structure is transferred once to the browser, and then the directories are opened or closed by changing the “display” style-property of the directories. To make this work we need to add two things to the HTML-page:

  1. the contents of every directory must be enclosed in a <span>-tag. As an example, we can use “Dir-C” in figure 3 above:

    With JavaScript, we can make this directory “disappear” by the statement

    and make it visible again by

    Again the “toggle” function will handle this for us.
  2. when a folder is opened or closed we must change the image depicting the folder. The technique for replacing images has been used for many years. If the image for the folder is called “f2” we display the “closed folder” image like this:

    and the “open folder” like this:

    This code is also placed in “toggle”.

Now we only need to make a new subclass of MyFileStructure. It’s called MyFileStructureJS, and it is almost identical to MyFileStructureExplorer. We only need to add the <span>-tags and the name of the folder-gif’s. Here is an outline of the class with the added code shown in bold:

To complete the code we also need a new version of the “toggle” JavaScript function:

If you try this solution I’m sure you’ll be impressed by the response times.


A Java-program for building a graphical view of a directory structure has been presented. When coding the open/close function we could choose between two solutions: one solved the job by letting Java-code on the server do the work. The other solution used JavaScript in the browser.

This is actually a rather common situation facing designers of web applications. A similar case is when you’ll have to decide how to handle validation of data entered in an HTML form. You can validate in the browser using JavaScript, or you can let the server handle it. Or you can use a mixture of these techniques. What you should prefer depends on your application. If fast response times are essential then use JavaScript. If the data will be written to a database, or are used for other critical operations you should (also) validate on the server.