Activity #2: Packages and Events

by Steve Hirst
Version 1.0 —27-Aug-97

Java source code and packages

Java class names are closely tied to the filenames and to the directory structures where the compiled classes are stored. To begin with all java source files must be named <class-name>.java where <class-name> is the name of a public class declared in the file. So the HelloWeb.java file declares public class HelloWeb …; when this file is compiled the output is put in the file HelloWeb.class. In C++ there is the concept of a compilation unit; if you take a source file include all the #include files and preprocess the file the result is a compilation unit and any name used in the source must be declared in the compilation unit. The closest concept to this in Java is the package.

A package is a set of classes; all the class file are stored together; while you are compiling and developing all the class files must be in a directory the same name as the package. (for purposes of installing a developed package the class files may be stored in a '.zip' file or a '.jar' file; we'll get to that later). The directory is stored relative to your CLASSPATH. All classes defined are visible to each other; classes defined a public are also visible to classes in other packages. By default, the CLASSPATH consists of the builtin java classes and the working directory. Packages can be nested by nesting the directories containing them.

Any class in any package reachable from the CLASSPATH can be used in a Java program by using the fully qualified name. For example, in JEA#1, HelloWeb was defined as: public class HelloWeb extends java.applet.Applet. This declares the HelloWeb is a public class (i.e. available to all packages) and is derived from the class Applet in the package java.applet. The import statement, allows you to refer to classes with just the class name. For example, including the statement import java.applet.Applet in HelloWeb.java, would let you define the class as: public class HelloWeb extends Applet. Notice, the import statement does not change the visibility of the class; it only makes typing the fully qualified name unnecessary. The statement import java.applet.*; allows short references to all the public classes in the package java.applet.

If you do not declare otherwise, classes belong to the default package and are assumed to be located at the root relative to the class path. In order to place a class in a named package, the first non-comment statement must be a package statement. Adding package activity to HelloWeb.java places the class HelloWeb in the package activity. The -d option on the java compiler command (javac) will instruct the compiler where to place the classes and the directories required for the files being compiled. If you change HelloWeb.java to place the class in package activity and compile it with the command: javac -d . HelloWeb.java then the HelloWeb will be put in a subdirectory activity the working directory (it will create the directory if necessary). For more examples, look at The Java Package Tutorial.

Member visibility

Threre are four levels of member access in Java: private, protected, public, and package. The syntax is as follow:
 
Levels of visibility
access level example where visible
private private int myValue;  only in the containing class
protected protected int sharedValue; in containing class,derived classes 

and all classes in the same package.

public public int getValue()  any class that can see the contain package
package int ourValue() all classes in the same package.
In C++, it is recommended that member variables be either private or protected. In Java, the same holds true with the additional caveat that making a member variable protected exposes your implementation to all the classes in the package. For more details see: Controlling Access to Members of a Class

Events

In Java 1.1 and later, user events (like mouse clicks and keystrokes) and system events (like windows opening and closing) are handled by registering an event listner with the object which is the target of the event. [Notice, this event model is new to JDK 1.1 and is not supported by Netscape 3 or Internet Explorer; when you write code with this model you have to use the appletviewer. Netscape support should be any day now in Netscape 4 and IE will come dragging along later.] The package java.awt.event defines interfaces for eleven different kinds of events: Package java.awt.event . We'll look at one the MouseEvents as an example. The java.awt.event package provides support for the following mouse events: mouse clicked, mouse pressed, mouse released, mouse entered and mouse exited. A class implementing the MouseListener interface must provide function definitions for all five: consider the following:
// Steve Hirst, NCS 28-Aug-97 
import java.awt.event.*; 
class MousePrintln implements MouseListener { 
   public void mouseClicked(MouseEvent e) { 
      System.out.println("mouseClicked"); 
   } 
   public void mouseEntered(MouseEvent e) { 
      System.out.println("mouseEntered"); 
   } 
   public void mouseExited(MouseEvent e) { 
      System.out.println("mouseExited"); 
   } 
   public void mousePressed(MouseEvent e) { 
      System.out.println("mousePressed"); 
   } 
   public void mouseReleased(MouseEvent e) { 
      System.out.println("mouseReleased"); 
   } 
}
This class responds to each mouse event by printing out its type. Note, the package java.awt.event also defines a class MouseAdapter with empty method bodies for all five events. This allows you to selectively override events of interest in derived classes. Note the distinction, when you extend a class you only declare the methods you want to override; when you implement an interface you must provide member functions (methods) for every method in the interface. MouseListener is an interface; MouseAdapter is a class. Every class can extend at most one superclass; but it may implement as many interfaces as you like. The full syntax is: <visibility keyword> class <name> extends <super-class> implements <interface-list>. More about this later; meanwhile you could check out:Objects, Classes, and Interfaces

Activity: at last

  1. Copy and compile the MousePrintln code above.
  2. Modify your HelloWeb.java code to include the following statement in its init() method: addMouseListener(new MousePrintln());
  3. Run the applet in the appletviewer and notice the various kinds of events.  When does a mouseClicked event happen?

Combining the steps:

Create a new HelloWeb.java file (or edit your earlier work) to look like the following: 
// The Hello World for Java
// Steve H. 19-Aug-97
package activity;

public class HelloWeb extends java.applet.Applet {
   private String message;
   int xPosition;
   int yPosition;
   int xBall;
   int yBall;
   void setPosition( int x, int y ) {
      xPosition=x;
      yPosition=y;
      repaint();
      }
   public void init() {
      message = getParameter("message");
      addMouseListener( new OnClick() );
      xPosition = 25;
      yPosition = 60;
      xBall = 50;
      yBall = 10;
      }
   public void paint( java.awt.Graphics gc ) {
     gc.fillOval(xBall,yBall,10,10);
     gc.drawString(message, xPosition, yPosition);
     gc.drawLine(1,1,xPosition,yPosition);
     }
}




This new version contains a number of differences from your code from activity #1:
  1. It has been placed in a package activity
  2. It defines a new method setPosition that changes the position of the message and causes a redraw
  3. And, it creates an instance of the class OnClick and adds it to the list of MouseListeners.
A file OnClick.java should be created containing the following code:

// OnClick listens for mouse clicks in HelloWeb // Steve Hirst; 21-Aug-97 package activity; import java.awt.event.*; class OnClick extends MouseAdapter {    public void mouseReleased( MouseEvent e) {      int newX = e.getX();      int newY = e.getY();      HelloWeb theApplet = (HelloWeb) e.getComponent();      theApplet.setPosition(newX,newY);    } }
Comments: the mouseReleased method is called by the system with one argument of Class java.awt.event.MouseEvent when the user release the mouse in the target area. The methods getX and getY do pretty much what you would expect. The getComponent call get the componenet receiving the event (we will do components next activity) in this case it returns a reference to our applet. With, this reference we can call the setPosition method (which has package visibility).

More Acitivity

  1. Modify HelloWeb.java to match the above code; create OnClick.java; compile both with '-d .' option (you'll have to compile OnClick.java first). Then modify your html document to refer to activity.HelloWeb.class and run appletviewer.
  2. When that works, add the following lines to HelloWeb's init() method:

  3. java.awt.Button change = new java.awt.Button("Change Color");
    add(change);
  4. Recompile and run appletviewer.
  5. Finaly, create a method to set Text color and use it to control the color of the message text (Go look at: Class java.awt.Graphics ); create a MouseListener for Button change and add it it's MouseListener list; test it our with appletviewer
  6. Beyond finally, look at the other listener interfaces; mess with a couple of them, maybe create Listeners like MousePrintln and attach them to either the applet or the button.

Looking ahead

Next time, we we'll talk about classes and objects; class and object methods; constructors and finalizer. Also we will look at the java.awt.Component class that most of the gui stuff is derived from. Have fun, sorry this activity was so wordy.