TweetFollow Us on Twitter

OS Shell In Java

Volume Number: 15 (1999)
Issue Number: 1
Column Tag: JavaTech

Writing an OS Shell in Java

by Andrew Downs

Building a Facade

Introduction

This article describes the design and implementation of a Finder-like shell written in Java. Several custom classes (and their methods) areexamined: these classes provide a subset of the Macintosh Finder's functionality. The example code presents some low-level Java programming techniques, including tracking mouse events, displaying images, and menu and folder display and handling. It also discusses several high-level issues, such as serialization and JAR files.

Java provides platform-dependent GUI functionality in the Abstract Windowing Tookit (AWT) package, and platform-independent look and feel in the new Java Foundation Classes (Swing) API. In order to faithfully model the appearance and behavior of one specific platform on another, it is necessary to use a combination of existing and custom Java classes. Certain classes can inherit from the Java API classes, while overriding their appearance and functionality. This article presents techniques used to create a Java application (Facade) that provides some of the Macintosh Finder's capabilities and appearance. As a Java application, it can theoretically run on any platform supporting the Java 1.1 and JFC APIs. Figure 1 provides an overview of the Facade desktop and its functionality. Figure 2 shows a portion of the underlying object model. It contains a mixture of existing Java classes (such as Component and Window) and numerous custom classes. In the diagram, the user interface classes are separated from the support classes for clarity.


Figure 1. Facade on Windows 95.


Figure 2. Facade object model (partial). Only the inheritance structure is shown; relational attributes are not shown.

The Object Model

Facade's object model utilizes the core Java packages and classes where possible. However, in order to provide the appropriate appearance and speed, custom versions of several standard Java classes were added. For instance, the DesktopFrame class is used to display folder contents. Its functionality is similar to the java.awt.Frame class. However, additional behavior (i.e. window-shade) and appearance requirements dictated the creation of a "knockoff" class.

One advantage of using custom classes can be improved speed. This holds true for classes inheriting from java.awt.Component: such classes do not require the creation of platform-specific "peer" objects at runtime. Less baggage results in a faster response. For example, the Facade menu display and handling classes respond very quickly.

In the custom classes, most drawing uses primitive functions to draw text, fill rectangles, etc. Layout and display customization is assisted through the use of global constant values which typically signify offsets from a particular location (as opposed to hardcoded coordinates).

Several of the classes depicted in the object model will be discussed in this article.

Appearance and Functionality

Facade relies on several graphical user interface classes in order to provide a Finder-like interface. These classes fall into the following categories:

  • GUI
    • Desktop
    • Menus
    • Icons
    • Folders
  • Support
    • Startup
    • Timing
    • Constants

Facade provides a subset of the following operations:

  • Menu and menu item selection
  • Displaying volume/folder contents
  • Dragging icons
  • Opening and closing windows
  • Managing the trash
  • Saving the desktop state at shutdown (exit)
  • Restoring the desktop state at startup
  • Launching applications
  • Dialog display
  • Cut/Copy/Paste
  • Changing the cursor
  • Emulating the desktop database

Several of these operations (and the classes which implement them) will be discussed in the following sections.

The Desktop

The Desktop class is a direct descendant of the java.awt.Window class, which provides a container with no predefined border (unlike the java.awt.Frame class). This approach allows the drawing and positioning of elements within the Desktop area, without needing to hide the platform-specific scrollbars, title bar, etc.

However, this approach means that special care and feeding is required to make the menubar work properly. In the current implementation, menubar (and menu) drawing is done directly in the Desktop class, using values obtained from those respective classes. In other words, menus don't draw themselves, Desktop does it for them.

Menu Creation

The following code snippet (Listing 1), taken from the Desktop constructor, creates the Apple menu, and populates it with one item. The menu is an instance of the DesktopImage class. The Apple icon (imgApple) was loaded further up in this method. A similar sequence creates and populates the File menu.

Listing 1: Desktop constructor

Desktop constructor
Creating menus in the Desktop constructor.

// ----------------------------------
//		* Desktop constructor
// ----------------------------------

Desktop() {

  // <snip>

  // Create the menus and their menu items.
  DesktopImageMenu dim;
  Vector vectorMenuItems;
  DesktopMenuItem dmi;
  // Calculate the y-coordinate of the menus (constant).
  int newY = this.getY() + this.getMenuBarHeight() -
   ( this.getMenuBarHeight() / 3 );
		
  // Calculate the x-coordinate of the menus (variable).
  int newX = this.getX();
  // Create the Apple menu.
  dim = new DesktopImageMenu();
  dim.setImage( imgApple.getImage() );
  dim.setX( imgApple.getX() );
  dim.setY( imgApple.getY() );
  // Create menu item "About..."
  dmi = new DesktopMenuItem( Global.menuItemAboutMac );
  dmi.setEnabled( true );
  // Add the menu item to the Vector for this particular menu...
  dim.getVector().addElement( dmi );
  // ...then tell the menu to calculate the item position(s).
  // Note that the Desktop's FontMetrics object gets used here.
  dim.setItemLocations( this.getGraphics().getFontMetrics() );
  // Add the Apple menu to the menubar's Vector.
  // The menubar was instantiated further up in this method.
  dmb.getVector().addElement( dim );
  // For the next menu, calculate its x-coordinate.
  newX = imgApple.getX();
  newX += ( 2 * Global.defaultMenuHSep );
  newX += ( ( DesktopImageMenu )dmb.getVector().elementAt( 0 )
   ).getImage().getWidth( this ); // Line wrap.
  DesktopMenu dm;
  // Create the File menu...
  dm = new DesktopMenu();
  dm.setLabel( Global.menuFile );
  dm.setX( newX );
  dm.setY( newY );
  // ...and all its menu items.
  dmi = new DesktopMenuItem( Global.menuItemNew );
  dmi.setEnabled( true );
  dm.getVector().addElement( dmi );
  dmi = new DesktopMenuItem( Global.menuItemOpen );
  dmi.setEnabled( false );
  dm.getVector().addElement( dmi );
  dmi = new DesktopMenuItem( Global.menuItemClose );
  dmi.setEnabled( false );
  dm.getVector().addElement( dmi );
  // Tell the menu to calculate the item position(s).
  dm.setItemLocations( this.getGraphics().getFontMetrics() );
  // Add the File menu to the menubar's Vector.
  dmb.getVector().addElement( dm );
  newX += ( 2 * Global.defaultMenuHSep );
  newX += theFontMetrics.stringWidth( dm.getLabel() );
  // <etc.>
}

Here, the variable dim is an instance of the class DesktopImageMenu. This specialized menu class simply adds an instance variable that contains an Image (in this case, the Apple) to the DesktopMenu class. Its behavior is the same as other menus, except that instead of a String it displays its Image. The x and y coordinates of this menu are determined by the same values assigned to the image when it was loaded.

This object contains one menu item, the "About" item. That item is enabled, and added to the Vector for the menu. This Vector contains all the menu items for that menu. This approach provides an easy way to manage and iterate over the menu items.

Once the Vector has been setup, its contents are given their x-y coordinates for drawing and selection purposes through the setItemLocations() method. Although this calculation can be done when the menu is selected, the code runs faster if those numbers are calculated and assigned at startup time.

Finally, the menu is added to the Vector for the menubar. The menubar uses a Vector to iterate over its menus, in the same way the menus iterate over their menu items. This will become apparent when examining the mouse-event handling code for the Desktop class.

The same approach is shown for the File menu, except that File contains a String instead of an Image, as well as several menu items.

Menu and Menu Item Selection

This class defines some global values that are shared between the Display and ModeSelector classes. These values are collected in one place to simplify housekeeping and maintenance. We will refer to them from the other classes as Global.NORMAL, Global.sleep, etc. This is the Java syntax for referencing static (class) attributes. Note that final means the values cannot be changed after they are initially assigned, so these are constants.


Figure 3. Menu item selection.

The code in Listing 2 handles mouseDown events in the menubar. The first two lines reset the instance variables used to track the currently active menu and menu item. Since the user has pressed the mouse, the old values do not apply. Next, the Graphics and corresponding FontMetrics objects for the Desktop instance are retrieved. They will be used in drawing and determining what selection the user has made.

Next, test to see whether the event occured within the bounding rectangle of the menubar. This line uses the java.awt.Component.contains() method. If the x-y coordinates of the mouse event are inside the menubar, then determine which menu (if any) the user selected.

Determining the menu selection uses the menubar's Vector of menus. Iterate over the Vector elements, casting each retrieved element to a DesktopMenu object. (Vector.elementAt() returns Object instances by default, which won't work here.) The menu has its own bounding rectangle, which is compared to the event x-y coordinates. In addition, in order to duplicate the Finder, a fixed pixel amount is subtracted from the left-side of the bounding rectangle, and added to the right-side. This allows the user to select near, but not necessarily directly on, the menu name (or image). Notice also in the (big and nasty) if conditional that the DesktopMenu retrieved from the Vector is checked for an Image (this handles the Apple menu). If it has one, the image width is used instead of the String width.

Once the user's menu selection has been found, it is redrawn with a blue background. Then, the menu items belonging to that menu are drawn inside a bounding rectangle (black text on white background). The menu item coordinates, and the corresponding bounding rectangle coordinates, were calculated when the menu was created, saving some CPU cycles here.

Listing 2: mousePressed

mousePressed
The mousePressed method handles menu selections.

// ----------------------------------
//		* mousePressed
// ----------------------------------

public void mousePressed( MouseEvent e ) {

  // New click means no previous selection.
  this.activeMenu = -1;
  this.activeMenuItem = -1;
  Graphics g = this.getGraphics();
  FontMetrics theFontMetrics = g.getFontMetrics();
  if ( dmb.contains( e.getX(), e.getY() ) ) {
   // Handle menu selection.
   for ( int i = 0; i < dmb.getVector().size(); i++ ) {
     // Get menu object.
  DesktopMenu d = ( DesktopMenu )dmb.getVector().elementAt( i );
     // Determine if we're inside this menu.
     // This could be done with one or more Rectangles.
     // Note the (buried) conditional operator: it accounts
     // for both text and image (e.g. the Apple) menus.
     if ( ( e.getX() >= d.getX() - Global.defaultMenuHSep ) 
     && ( e.getX() <= ( d.getX() + ( d.getLabel() == null ? 
      ( ( DesktopImageMenu )d ).getImage().getWidth( this ) :
      theFontMetrics.stringWidth( d.getLabel() ) ) +
      Global.defaultMenuHSep ) ) 
     && ( e.getY() >= this.getY() ) && ( e.getY() <=
      this.getMenuBarHeight() ) ) {
      // Draw menubar highlighting...
      g.setColor( Color.blue );
      // Save the current Rectangle surrounding the menu.
      // This will speed up painting on the following line,
      // and when the user leaves this menu.
      activeMenuRect = new Rectangle( d.getX() -
        Global.defaultMenuHSep, this.getY(), ( d.getLabel() ==
        null ? ( ( DesktopImageMenu )d ).getImage().getWidth(
        this ) : theFontMetrics.stringWidth( d.getLabel() ) ) + 
        ( 2 * Global.defaultMenuHSep ), getMenuBarHeight() );
      g.fillRect( activeMenuRect.x, activeMenuRect.y,
        activeMenuRect.width, activeMenuRect.height );
      // Draw menu String or Image.
      g.setColor( Color.black );
      if ( d.getLabel() != null )
        g.drawString( d.getLabel(), d.getX(), d.getY() );
      else
        g.drawImage( ( ( DesktopImageMenu )d ).getImage(),
         d.getX(), d.getY(), this );
				
      // Get menu item vector.
      Vector v = d.getVector();
      // If the Trash is full, enable the menu item.
      // This code can easily be moved; it is included
      // here for illustration.
      DesktopMenuItem dmi = 
        ( DesktopMenuItem )v.elementAt( 0 );
    if ( dmi.getLabel().equals( Global.menuItemEmptyTrash ) ) {
        DesktopImage di = ( ( DesktopImage
         )this.vectorImages.elementAt( 1 ) );
        String path = di.getPath();
        File f = new File( path, Global.trashDisplayString );
        if ( f.exists() ) {
         String array[] = f.list();
							
         if ( array == null || array.length == 0 )
           dmi.setEnabled( false );
         else
           dmi.setEnabled( true );
        }
      }

      // Draw menu background.
      g.setColor( dmb.getBackground() );
      g.fillRect( d.getItemBounds().getBounds().x,
        d.getItemBounds().getBounds().y,
        d.getItemBounds().getBounds().width,
        d.getItemBounds().getBounds().height );
      // Draw menu items.
      for ( int j = 0; j < v.size(); j++ ) {
        g.setColor( Color.black );
        if ( !( ( DesktopMenuItem )v.elementAt( j )
         ).getEnabled() )
         g.setColor( Color.lightGray );
        g.drawString( ( ( DesktopMenuItem )v.elementAt( j )
         ).getLabel(), ( ( DesktopMenuItem )v.elementAt( j )
         ).getDrawPoint().x,
         ( ( DesktopMenuItem )v.elementAt( j )
         ).getDrawPoint().y );
      }
      g.setColor( Color.black );
      // Outline the menu item list bounding rectangle.
      g.drawRect( d.getItemBounds().getBounds().x,
        d.getItemBounds().getBounds().y,
        d.getItemBounds().getBounds().width,
        d.getItemBounds().getBounds().height );
      // Add horizontal drop shadow.
      g.fillRect( d.getItemBounds().getBounds().x + 2,
        d.getItemBounds().getBounds().y +
        d.getItemBounds().getBounds().height,
        d.getItemBounds().getBounds().width, 2 );
      // Add vertical drop shadow.
      g.fillRect( d.getItemBounds().getBounds().x +
        d.getItemBounds().getBounds().width,
        d.getItemBounds().getBounds().y + 2, 2,
        d.getItemBounds().getBounds().height );
      // Set current menu.
      this.activeMenu = i;
      // Once found, we're done.
      break;
     }
   }
  }
}

The mouseDragged() method (not shown) is responsible for the highlighting and unhilighting of menus and menu items: that is where menu items get redrawn with white text on a blue background, as depicted in Figure 3.

Displaying Folder Contents

Folders in Facade use a combination of core Java classes and Swing classes. The container itself descends from java.awt.Window, and the paint() method performs the low-level drawing calls (drawing the title bar, close box, etc.). The content is displayed inside a JScrollPane.

Once the Macintosh look-and-feel is activated, the scrollbars take the appearance shown in Figure 4. The icons within the scrollpane are added to a grid layout. This approach works well, except that the tendency of the scrollpane is to take up the entire display area (ignoring the title bar, etc.). So, on resize of the container, the scrollpane is also resized. A java.awt.Insets object is used to make this as painless as possible: the Insets values are used as the buffer area around the scrollpane.

Like most of the Facade classes, DesktopFolder implements the MouseListener and MouseMotionListener interfaces so it can receive mouse events. Within the methods required for those interfaces, the x-y coordinates are checked to determine if a close, zoom, shade, grow, or drag operation is taking place, and the container gets reshaped appropriately.


Figure 4. Displaying folder contents.

Listing 3: addFileTree

addFileTree
Building a folder's display area.

// ----------------------------------
//		* addFileTree
// ----------------------------------

public void addFileTree( String s ) {
  // Instantiate the instance variables for this object's content.
  // The Mac L&F requires both scrollbars.
  pane = new JScrollPane();
  pane.setHorizontalScrollBarPolicy( 
   JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
  pane.setVerticalScrollBarPolicy( 
   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
  // Make sure the argument passed in is a valid directory.
  String defaultVolume = s;
  if ( defaultVolume == null )
   return;
		
  File theDir = new File( defaultVolume );
  if ( !theDir.isDirectory() )
   return;
  // Retrieve the contents of this folder/directory.
  contents = theDir.list();
  int tempLength = 0;
  if ( contents != null ) {
   tempLength = contents.length;
  // Use a Swing panel inside the Swing scrollpane.
  // Default to a grid layout simply because it looks the best.
  JPanel p = new JPanel();
  p.setLayout( new GridLayout( 5, 3, 5, 5 ) );
  // If the contents contain full path specifications, there will
  // be some extraneous characters that we don't want to display.
  char pathSeparatorChar = theDir.pathSeparatorChar;
  char separatorChar = theDir.separatorChar;
  Vector v = new Vector();
  v.addElement( Global.spaceSep );
  int loc = 0;
  int k = 0;
		
  for ( int j = 0; j < tempLength; j++ ) {
   // For each item, separator chars should become spaces for 
   // display purposes.
   File tempFile = new File( theDir, contents[ j ] );
   contents[ j ] = 
 new String( contents[ j ].replace( pathSeparatorChar, ' ' ) );
   contents[ j ] = 
     new String( contents[ j ].replace( separatorChar, ' ' ) );
   for ( int l = 0; l < v.size(); l++ ) {
     // Parse root volume name.
     // Remove leading '%20' character.
     loc = contents[ j ].indexOf( ( String )v.elementAt( l ) );
     if ( loc == 0 )
      contents[ j ] = new String( contents[ j ].substring( ( 
        ( String )v.elementAt( l ) ).length() ) );
     // Volume name includes first '%20'.
     // Rework this for MacOS.
     loc = contents[ j ].indexOf( ( String )v.elementAt( l ) );
     // Build the final display String from substrings.
while ( ( loc > 0 ) && ( loc < contents[ j ].length() + 1 ) ) {
   String s1 = new String( contents[ j ].substring( 0, loc ) );
      String s2 = new String( contents[ j ].substring( loc + ( 
        ( String )v.elementAt( l ) ).length() ) );
      contents[ j ] = new String( s1 + " " + s2 );
    loc = contents[ j ].indexOf( ( String )v.elementAt( l ) );
     }
   }

   // Now build the appropriate icon.
   Image theImage;
   int tempWidth = 0;
   DesktopFrameItem d;
   ImageIcon ii = new ImageIcon();
   // Files obviously look different than folders.
   // Set the appropriate Image.
   // This version does not handle mouse clicks on documents.
   if ( tempFile.isFile() ) {
     d = new DesktopDoc();
     ii = new ImageIcon( ( ( DesktopDoc )d ).getImage() );
   }
   else {
     d = new DesktopFolder();
     ii = new ImageIcon( ( ( DesktopFolder )d ).getImage() );
     d.addMouseListener( ( DesktopFolder )d );
   }

   // Set the display Strings.
   d.setLabel( contents[ j ] );
   d.setText( contents[ j ] );
   // Set the path for the item. It is built from the parent folder
   // path and filename.
   d.setPath( this.getPath() + 
     System.getProperty( "file.separator" ) + contents[ j ] );
   // And set the icon.
   d.setIcon( ii );
   // Swing methods for positioning the icon and label.
   d.setHorizontalAlignment( JLabel.CENTER );
   d.setHorizontalTextPosition( JLabel.CENTER );
   d.setVerticalTextPosition( JLabel.BOTTOM );
   ii.setImageObserver( d );
   // Add the completed item to the panel.
   p.add( d );
  }

  // Set the panel characteristics, then add it to the scrollpane.
  p.setVisible( true );
  pane.getViewport().add( p, "Center" );
  pane.setVisible( true );
  // A container within a container within a container...it works.
  panel = new JPanel();
  panel.setLayout( new BorderLayout() );
  panel.add( pane, "Center" );
  this.add( panel );
  // Use the Insets object for this window to set the viewing
  // size of the panels and scrollpane.
  panel.reshape( this.getInsets().left, this.getInsets().top, 
   this.getBounds().width - this.getInsets().right - 
   this.getInsets().left, this.getBounds().height - 
   this.getInsets().top - this.getInsets().bottom 
  // Ready for display.
  panel.setVisible( true );
  this.pack();
  this.validate();
}

The Trash

The trash is simply a directory located at the root of the volume (for example, c:\Trash). Items can be dragged onto the trash can icon, the mouse button released, and the item (and its contents, if it is a folder) are moved to the trash directory. If the item has an open window, that window is destroyed. Emptying is accomplished through the "Empty Trash..." menu item in the Special menu. Figure 5 shows a folder being dragged to the trash. The cursor did not get captured in the image, but it is positioned over the trash icon, ready to release the folder.


Figure 5. Dragging a folder to the Trash.

The code in Listing 4 handles the "Empty Trash..." menu item. If a match is found between the selected item and the constant assigned as the Trash label, the path to the Trash is retrieved. Once the code determines the "Trash" is indeed an existing directory, the emptyDir() method is called. Once emptyDir() returns, the icon is changed from full to empty. Note that the trash icon is always present in the vectorImages object. This Vector contains the known images (icons) for items on the desktop. The trash is always at position 0, the first position. The root volume is at position 1. This allows quick, though hardcoded, access to the images when repainting occurs, or an image needs swapping.

Listing 4: handleMenuItem

handleMenuItem
Handling the "Empty Trash..." menu item.

// ----------------------------------
//		* handleMenuItem
// ----------------------------------

public boolean handleMenuItem() {
  boolean returnValue = false;
  // Handle active menu item.
 if ( ( this.activeMenu != -1 ) && ( this.activeMenuItem != -1 ) ) {
   // Get menu object.
   DesktopMenu dm = 
   ( DesktopMenu )dmb.getVector().elementAt( this.activeMenu );
   // Get menu item.
   String s = ( ( DesktopMenuItem )dm.getVector().elementAt(
     this.activeMenuItem ) ).getLabel();
   // <snip>
   if ( s.equals( Global.menuItemEmptyTrash ) ) {
     // The path to the trash is assumed to be of the form:
     //  <root vol>/Trash
     DesktopImage di = 
      ( ( DesktopImage )this.vectorImages.elementAt( 1 ) );
     String path = di.getPath();
     File f = new File( path, Global.trashDisplayString );
     // Once we have the object that references the Trash dir...
     if ( f.exists() && f.isDirectory() ) {
      // Call the method which empties it.
      boolean b = this.emptyDir( f );
      // If successful, change the icon back to empty.
      if ( b ) {
        // Save the current bounds. We really want the x-y.
        Rectangle r =
         ( ( DesktopImage )this.vectorImages.elementAt( 0 )
          ).getBounds();
        // Change the icon. imgTrash and imgTrashFull are two
        // instance variables, each referencing the appropriate
        // icon.
        this.vectorImages.setElementAt( this.imgTrash, 0 );
        ( ( DesktopImage )this.vectorImages.elementAt( 0 )
         ).setBounds( r );
        // Show the change.
        this.repaint();
      }
     }
   }
  }
}

Emptying the Trash

emptyDir() is displayed in Listing 5. This method will empty the specified directory recursively. As it finds each item in the directory, appropriate action is taken. If the item is a file it is immediately deleted. If it is a directory, emptyDir() is called again, with the subdirectory name as its argument. Eventually, all of the files in the subdirectory are deleted, and then the subdirectory itself is removed.

Listing 5: emptyDir

emptyDir
Emptying a directory.

// ----------------------------------
//		* emptyDir
// ----------------------------------

public boolean emptyDir( File dir ) {
  // Recursive method to remove a directory's contents,
  // then delete the directory.
  boolean b = false;
  // Get the directory contents.
  String array[] = dir.list();
  // If the path is screwed up, this will catch it.
  if ( array != null ) {
   // Iterate over the directory contents...
   for ( int count = 0; count < array.length; count ++ ) {
     String temp = array[ count ];
     // Create a new File object using path + filename.
     File f1 = new File( dir, temp );
     // Delete files immediately.
     // Call this method again for subdirectories.
     if ( f1.isFile() ) {
      b = f1.delete();
     }
     else if ( f1.isDirectory() ) {
      b = this.emptyDir( f1 );
      b = f1.delete();
     }
   }
  }
  return b;
}

Saving and Restoring State

Facade uses a variant on the standard Java serialization mechanism for saving the Desktop state. The code in Listing 6 illustrates the saving and restoring of open folder windows. Both of these methods are in the Desktop class. Note that rather than flatten entire DesktopFrame objects, this code saves only specific attributes from each object. The primary reason for this approach is that it avoids any exceptions thrown when attempting to serialize the Swing components and Images (which are not serializable by default) within each DesktopFrame. Another reason is the relative ease with which this approach may be implemented. Plus, it reduces the amount of data written to disk. One disadvantage is that the current scroll position of any open window is lost.

Listing 6: saveState and restoreState

saveState
Saving and restoring open DesktopFrames.

// ----------------------------------
//		* saveState
// ----------------------------------

private void saveState() {
  // The Desktop data will be stored in a file at the root level.
  DesktopImage di =
   ( ( DesktopImage )this.vectorImages.elementAt( 1 ) );
  String s = new String( di.getPath() + "Desktop.ser" );
  try {
   FileOutputStream fos = new FileOutputStream( s );
   ObjectOutputStream outStream = new ObjectOutputStream( fos );
   // Use a temporary Vector to hold the open DesktopFrames.
   // This should not be necessary when shutting down, but it
   // is a good habit to follow.
   Vector v = new Vector();
   v = ( Vector )this.vectorWindows.clone();
   // Use another temporary Vector to hold the attributes to save.
   Vector temp = new Vector();
			
   for ( int i = 0; i < v.size(); i++ ) {
     // For each DesktopFrame, we'll save its path, display 
     // string, and its bounding Rectangle. If window-shading is 
     // in effect on an object, restore the full height before 
     // saving.
     DesktopFrame df = ( DesktopFrame )v.elementAt( i );
     temp.addElement( df.getPath() );
     temp.addElement( df.getLabel() );
     if ( df.getShade() ) {
      df.restoreHeight();
     }
     temp.addElement( df.getBounds() );
   }
   // Write the Vector contents to the .ser file.
   outStream.writeObject( temp );
   outStream.flush();
   outStream.close();
  }
  catch ( IOException e ) {
   System.out.println( "Couldn't save state." );
   System.out.println( "s = " + s );
   e.printStackTrace();
  }
}

// ----------------------------------
//		* restoreState
// ----------------------------------

private void restoreState() {

  // The Desktop data is stored in a file at the root level.
  // This step occurs near the end of the Desktop constructor, 
  // and so can use the root volume to build the path.
  DesktopImage di = 
   ( ( DesktopImage )this.vectorImages.elementAt( 1 ) );
  String s = new String( "\\Desktop.ser" );
  try {
   // Open the file, and read the contents. In this version
   // we know it's just one Vector.
   FileInputStream fis = new FileInputStream( s );
   ObjectInputStream inStream = new ObjectInputStream( fis );
   Vector v = new Vector();
   v = ( Vector )inStream.readObject();
   inStream.close();
  Rectangle r = new Rectangle();
   for ( int i = 0; i < v.size(); i++ ) {
     // Iterate over the Vector contents. We know the save format:
     // each field corresponds to a specific attribute of a 
     // DesktopFrame.
     // Create a new DesktopFrame using the retrieved path.
     s = ( String )v.elementAt( i );
     DesktopFrame df = new DesktopFrame( s );
				
     // Set its label using the next Vector element.
     i++;
     s = ( String )v.elementAt( i );
     df.setLabel( s );
     // Set its bounding Rectangle using the next Vector element.
     i++;
     r = ( Rectangle )v.elementAt( i );
     df.setBounds( r );
     // Prepare and display the DesktopFrame.
     df.pack();
     df.validate();
     df.show();
     df.toFront();
     df.repaint();
     // Add the object to the Desktop's Vector of open windows.
     Desktop.addWindow( df );
   }
  }
  catch ( ClassNotFoundException e ) {
   System.out.println( "ClassNotFoundException in retrieveState()."
     );
  }
  catch ( IOException e ) {
   System.out.println( "Couldn't retrieve state." );
   System.out.println( "s = " + s );
   e.printStackTrace();
  }
}

Packaging (Facade in a JAR)

Facade can be run from a Java Archive (JAR) file, or as a set of separate classes plus images. In addition, the Macintosh look-and-feel classes must be present (usually in a separate JAR). The system environment variables need to be setup properly in order for the Java runtime to find the classes.

The JAR file for Facade was created like this:

  jar cf Facade.jar /Facade/*.class /Facade/*.gif

Once the environment variables are set, Facade can be invoked as follows:

  java Facade

Other Classes

In addition to the java.awt classes already discussed, there are other packages and classes used often in Facade.

This program relies heavily on the java.util.Vector class for maintaining a semblance of order among the various objects. Several Vector instances are used for tracking icons and open windows. Figure 6 illustrates the core concept of a Vector: it is a growable array.


Figure 6. Creating and populating a Vector. The arrow represents a pointer to the current element at the end of the Vector.

The java.io.File class provides most of the file system operations for display and management. Refer to the references provided in the bibliography for API details. One platform-specific detail that was not discussed is the translation of a root path to a form that is valid for a File directory object. For example, calling the File.list() method on the path "c:\" will not return any file or folder names, but calling the same method for the path "/" will return the root directory contents.

Facade also uses the Java Foundation Classes (Swing) to provide a consistent look and feel across platforms, primarily for window scrolling operations. Swing runs a bit slow right now, but as peformance improves Swing classes can be substituted for some of the Facade custom classes. For example, the code that handles folder content display can be modified to show a tree structure. This capability should be easy to implement using the Swing classes, with little additional low-level drawing code.

Conclusion

Writing Java classes to model operating system functionality requires some choices, particularly in the selection of pre-defined GUI classes. Although many classes are available, you will need to create others, since performance of the pre-defined classes may be slow, or the behavior may not be exactly what you need. Both the appearance and behavior for custom GUI elements must be written.

This article touched on several key areas: desktop layout, menu and mouse handling, icon display and movement, the trash, and saving and restoring the desktop state. All of these functional areas can be modeled easily using the Java 1.1 classes, supplemented by JFC and custom-built classes.

References

  • Developing Java Beans, Robert Englander, O'Reilly & Associates, Inc., 1997.
  • Java in a Nutshell, David Flanagan, O'Reilly & Associates, Inc., 1997.
  • Exploring Java, Patrick Niemeyer and Joshua Peck, O'Reilly & Associates, Inc., 1997.
  • Programming with JFC, Scott Weiner and Stephen Asbury, John Wiley & Sons, Inc., New York, NY, 1998.

URLs


Andrew Downs is a Technical Lead for Template Software in New Orleans, LA, designing and building enterprise apps. When he's not dodging hurricanes, he watches his twin sons stress test Macintosh hardware. Andrew wrote the Macintosh freeware program Recent Additions, and the Java application UDPing. You can reach him at andrew@nola.template.com.

 
AAPL
$102.23
Apple Inc.
+2.47
MSFT
$44.61
Microsoft Corpora
+0.53
GOOG
$520.91
Google Inc.
+0.07

MacTech Search:
Community Search:

Software Updates via MacUpdate

NTFS 12.0.39 - Provides full read and wr...
Paragon NTFS breaks down the barriers between Windows and OS X. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS, providing full read and write access to... Read more
RestoreMeNot 2.0.3 - Disable window rest...
RestoreMeNot provides a simple way to disable the window restoration for individual applications so that you can fine-tune this behavior to suit your needs. Please note that RestoreMeNot is designed... Read more
Macgo Blu-ray Player 2.10.9.1750 - Blu-r...
Macgo Mac Blu-ray Player can bring you the most unforgettable Blu-ray experience on your Mac. Overview Macgo Mac Blu-ray Player can satisfy just about every need you could possibly have in a Blu-ray... Read more
Apple iOS 8.1 - The latest version of Ap...
The latest version of iOS can be downloaded through iTunes. Apple iOS 8 comes with big updates to apps you use every day, like Messages and Photos. A whole new way to share content with your family.... Read more
TechTool Pro 7.0.5 - Hard drive and syst...
TechTool Pro is now 7, and this is the most advanced version of the acclaimed Macintosh troubleshooting utility created in its 20-year history. Micromat has redeveloped TechTool Pro 7 to be fully 64... Read more
PDFKey Pro 4.0.2 - Edit and print passwo...
PDFKey Pro can unlock PDF documents protected for printing and copying when you've forgotten your password. It can now also protect your PDF files with a password to prevent unauthorized access and/... Read more
Yasu 2.9.1 - System maintenance app; per...
Yasu was originally created with System Administrators who service large groups of workstations in mind, Yasu (Yet Another System Utility) was made to do a specific group of maintenance tasks... Read more
Hazel 3.3 - Create rules for organizing...
Hazel is your personal housekeeper, organizing and cleaning folders based on rules you define. Hazel can also manage your trash and uninstall your applications. Organize your files using a... Read more
Autopano Giga 3.7 - Stitch multiple imag...
Autopano Giga allows you to stitch 2, 20, or 2,000 images. Version 3.0 integrates impressive new features that will definitely make you adopt Autopano Pro or Autopano Giga: Choose between 9... Read more
MenuMeters 1.8 - CPU, memory, disk, and...
MenuMeters is a set of CPU, memory, disk, and network monitoring tools for Mac OS X. Although there are numerous other programs which do the same thing, none had quite the feature set I was looking... Read more

Latest Forum Discussions

See All

Clips Review
Clips Review By Jennifer Allen on October 21st, 2014 Our Rating: :: CONVENIENT PASTINGUniversal App - Designed for iPhone and iPad Making copying and pasting more powerful than usual, Clips is a great way to move stuff around.   | Read more »
MonSense Review
MonSense Review By Jennifer Allen on October 21st, 2014 Our Rating: :: ORGANIZED FINANCESiPhone App - Designed for the iPhone, compatible with the iPad Organize your finances with the quick and easy to use, MonSense.   | Read more »
This Week at 148Apps: October 13-17, 201...
Expert App Reviewers   So little time and so very many apps. What’s a poor iPhone/iPad lover to do? Fortunately, 148Apps is here to give you the rundown on the latest and greatest releases. And we even have a tremendous back catalog of reviews; just... | Read more »
Angry Birds Transformers Review
Angry Birds Transformers Review By Jennifer Allen on October 20th, 2014 Our Rating: :: TRANSFORMED BIRDSUniversal App - Designed for iPhone and iPad Transformed in a way you wouldn’t expect, Angry Birds Transformers is a quite... | Read more »
GAMEVIL Announces the Upcoming Launch of...
GAMEVIL Announces the Upcoming Launch of Mark of the Dragon Posted by Jessica Fisher on October 20th, 2014 [ permalink ] Mark of the Dragon, by GAMEVIL, put | Read more »
Interview With the Angry Birds Transform...
Angry Birds Transformers recently transformed and rolled out worldwide. This run-and-gun title is a hit with young Transformers fans, but the ample references to classic Transformers fandom has also earned it a place in the hearts of long-time... | Read more »
Hail to the King: Deathbat Review
Hail to the King: Deathbat Review By Rob Thomas on October 20th, 2014 Our Rating: :: SO FAR AWAYUniversal App - Designed for iPhone and iPad Hail to the King: Deathbat may feel like “Coming Home” for Avenged Sevenfold’s faithful,... | Read more »
Find Free Food on Campus with Ypay
Find Free Food on Campus with Ypay Posted by Jessica Fisher on October 20th, 2014 [ permalink ] iPhone App - Designed for the iPhone, compatible with the iPad | Read more »
Strung Along Review
Strung Along Review By Jordan Minor on October 20th, 2014 Our Rating: :: GOT NO STRINGSUniversal App - Designed for iPhone and iPad A cool gimmick and a great art style keep Strung Along from completely falling apart.   | Read more »
P2P file transferring app Send Anywhere...
File sharing services like Dropbox have security issues. Email attachments can be problematic when it comes to sharing large files. USB dongles don’t fit into your phone. Send Anywhere, a peer-to-peer file transferring application, solves all of... | Read more »

Price Scanner via MacPrices.net

Strong iPhone, Mac And App Store Sales Drive...
Apple on Monday announced financial results for its fiscal 2014 fourth quarter ended September 27, 2014. The Company posted quarterly revenue of $42.1 billion and quarterly net profit of $8.5 billion... Read more
Apple Posts How-To For OS X Recovery
OS X 10.7 Lion and later include OS X Recovery. This feature includes all of the tools you need to reinstall OS X, repair your disk, and even restore from a Time Machine backup. OS X Recovery... Read more
Mac OS X Versions (Builds) Supported By Vario...
Apple Support has posted a handy resource explaining which Mac OS X versions (builds) originally shipped with or are available for your computer via retail discs, downloads, or Software Update. Apple... Read more
Deals on 2011 13-inch MacBook Airs, from $649
Daily Steals has the Mid-2011 13″ 1.7GHz i5 MacBook Air (4GB/128GB) available for $699 with a 90 day warranty. The Mid-2011 13″ 1.7GHz i5 MacBook Air (4GB/128GB SSD) is available for $649 at Other... Read more
2013 15-inch 2.0GHz Retina MacBook Pro availa...
B&H Photo has leftover previous-generation 15″ 2.0GHz Retina MacBook Pros now available for $1599 including free shipping plus NY sales tax only. Their price is $400 off original MSRP. B&H... Read more
Updated iPad Prices
We’ve updated our iPad Air Price Tracker and our iPad mini Price Tracker with the latest information on prices and availability from Apple and other resellers, including the new iPad Air 2 and the... Read more
Apple Pay Available to Millions of Visa Cardh...
Visa Inc. brings secure, convenient payments to iPad Air 2 and iPad mini 3as well as iPhone 6 and 6 Plus. Starting October 20th, eligible Visa cardholders in the U.S. will be able to use Apple Pay,... Read more
Textkraft Pocket – the missing TextEdit for i...
infovole GmbH has announced the release and immediate availability of Textkraft Pocket 1.0, a professional text editor and note taking app for Apple’s iPhone. In March 2014 rumors were all about... Read more
C Spire to offer iPad Air 2 and iPad mini 3,...
C Spire on Friday announced that it will offer iPad Air 2 and iPad mini 3, both with Wi-Fi + Cellular, on its 4G+ LTE network in the coming weeks. C Spire will offer the new iPads with a range of... Read more
Belkin Announces Full Line of Keyboards and C...
Belkin International has unveiled a new lineup of keyboard cases and accessories for Apple’s newest iPads, featuring three QODE keyboards and a collection of thin, lightweight folios for both the... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** At the Apple Store, you connect business professionals and entrepreneurs with the tools they need in order to put Apple solutions to work in their Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.