Opening and closing the folders

Java Tutorial: Working with Files and Directories in Java:

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

Opening and closing the folders

To handle the “open/closed” status of a directory we first add             a new member variable and a couple of methods to MyDir:

 

 

“toggleOpen” simply switches “true” to “false” and vice versa. By setting “open” to “true” as default the whole directory structure will be shown initially. Using “false” will only show the top directory. It’s dependant upon the application as to which option will be the best default value.

The next thing is to add JavaScript code to the HTML-page that will issue requests to open and close the directories. If you look in the code for MyFileStructureExplorer above you’ll see that I’ve added a link around each folder. Furthermore I’ve added an onclick event that calls a JavaScript function “toggle” to open or close the folder. The “toggle” function must be defined in the HTML-page, and in the first solution we’ll use a simple design, where “toggle” requests a jsp-page with an id of the folder that should be opened or closed. A simple jsp-page, toggle.jsp, that contains “toggle” can look like this:

The “toggle” function simply calls another jsp-page, ctltoggle.jsp , which gets the id of the folder, calls a new method “toggleDir”, which flips the open/close status of the folder, and then returns to the first jsp-page again:

Before explaining how the id for the directory–the “key”–is implemented, let’s see how the output from the new jsp-pages looks:

– Figure 3 –

Nice, right? It’s not very far from figure 1. To get a good result you’ll have to use a small font like the one given in the style sheet above. A larger font may cause the vertical lines to break.

Clicking on the folders will make them open or close. As mentioned above the click event calls “toggle” with the id of the directory, e.g. <a href=”#” onclick=”toggle(1)”>. All directories are numbered 0,1,2,� and the id is used to look up the directory in a Vector of MyDir’s held by MyFileStructure. The few new lines to handle this in MyFileStructure are shown here: