CPSC 124, Fall 2005
Lab 9: Events and Applets

In this lab, you will be learning a little more about event-driven programming by writing a program that handles mouse events. A mouse generates several types of events (seven types in Java). You can program responses to any of these events. In the first exercise of the lab, you will respond by doing some simple drawing operations.

The second exercise of the lab asks you to set up a web site where you can display some of the work you have done. You will publish the work as "applets," which are small programs that run on a web page. You will not be required to learn a lot about web site programming, since you will just be modifying a small starter site that has already been created for you.

This lab is due, as usual, at next Tuesday's lab.

Handling Mouse Events

As usual, you can begin the lab by creating a new Java project in Eclipse. You should import the following three files from the directory /classes/f05/cs124/lab9/SourceCode: MouseEventsApplet.java, MouseEventsApplication.java, and MouseEventsDemo.java. The only file that you will have to edit is MouseEventsDemo.java. The main program is MouseEventsApplication.java, so you can run that file as a Java application. If you do this before editing the file, you'll get a window that just shows a gray rectangle. Clicking on this area will draw a small square centered at the point where you click; shift-clicking will draw a small oval. This drawing area of the program is a JPanel that is defined by the MouseEventsDemo class (which is a subclass of JPanel). It has already been programmed to respond to mouse clicks. You will be programming it to respond to other types of mouse events. The outline of the event handling has already been set up for you -- all you have to do is edit the methods in the class and add a few instance variables.

Java has a very flexible system for handling events. This means that there are various ways to design an event-driven program. This is good, but the unfortunate side of it is that there is no one correct way that you can learn once and for all. In this lab, you will write a program that handles mouse events, but you should be aware that the way the program works is not the only way, or even the best way, that the program could be designed.

One way for a program to receive mouse events is to "listen" for them. Any object can be a listener, as long as it defines certain event-handling methods. (This technique is described in Section 6.4, but you don't have to completely understand it to do the lab, because the basic event-handling has already been set up in MouseEventsDemo.java.) The methods that are required for handling mouse events are defined in two "interfaces". An interface is basically just a list of subroutines. There are two interfaces for handling mouse events. The MouseListener interface specifies the subroutines:

           public void mousePressed(MouseEvent e)
           public void mouseReleased(MouseEvent e)
           public void mouseClicked(MouseEvent e)
           public void mouseEntered(MouseEvent e)
           public void mouseExited(MouseEvent e)

The other interface is MouseMotionListener, which specifies two subroutines that handle events generated when the user moves the mouse:

           public void mouseMoved(MouseEvent e)
           public void mouseDragged(MouseEvent e)

For more information about each method, see the comments in MouseEventsDemo.java, or read Section 6.4.

Remember that these methods will be called by the system when the user does certain things with the mouse. You don't call the methods yourself -- you just have to define them to respond to the user's actions whenever they occur.

Note that each method has a parameter of type MouseEvent. This parameter is provided to you by the system when it calls the method. It contains information about the mouse event. You can get at this method by calling methods in the parameter object e. Here are some of the most useful methods in e:

In your program, you will respond to mouse events by drawing something on the panel. You will need a Graphics object to do any drawing. The format for obtaining and using an graphics object is:

          Graphics g = getGraphics();  // An object for drawing on this panel.
              .   // Use g to draw on the panel.
          g.dispose();  // Free the operating system resources used by g.

(Drawing in this way is not considered to be good style in modern Java, but we will do it anyway.)

You can see how the mouse event parameter and a graphics object are used in the mousePressed method in the original program:

    public void mousePressed(MouseEvent e) {
        Graphics g = getGraphics();   // For drawing on the panel.
        g.setColor( Color.RED );
        if (e.isShiftDown()) {
               // If the user is holding the shift key down,  
               // draw a circle centered at (e.getX(),e.getY())
            g.fillOval(e.getX() - 20, e.getY() - 20, 40, 40);
        else {
               // If the user is NOT holding shift down,  
               // draw a rectangle centered at (e.getX(),e.getY())
            g.fillRect(e.getX() - 20, e.getY() - 20, 40, 40);
        g.dispose();  // Frees resources used by the Graphics object.

Exercise 1: Your job is to modify the program to respond to other types of mouse events (and probably change mousePressed as well). Try to be creative. Grading will be partly completive, depending on what everyone in the class does. At a minimum, you are required to do something in response to either the mouseDragged or mouseMoved events, or both. In addition, you are required to do something that uses state variables to keep track of the state of the program between events. For example, you could count how many times the mouse has been pressed, and you could program different responses based on that number. Some more definite suggestions follow.

Here are some ideas for things that your applet could do:

Your CS124 Web Site

Java programs can be either applications or applets. An applet is a small program that runs in a rectangular area on a Web page. Applets are introduced in Section 6.1 of the textbook, and the basics of HTML, the languages that is used for writing web pages, are covered in Section 6.2. Lab 5 explained how you can publish an applet on the Math/CS department web server, but you were not required to do so at that time. This time around, it is required.

The MouseEvents program that you wrote for this lab can be run either as an application or as an applet. The file that you worked on, MouseEventsDemo.java, defines a JPanel. It is easy to use this JPanel in either a frame or in an applet. The application MouseEventsApplication.java is a short program that simply creates a JFrame and adds a MouseEventsDemo panel to it, so when you run this application, you see your mouse events panel in its own window. On the other hand, the file MouseEventsApplet.java defines a subclass of the JApplet class; this subclass defines an applet that displays a MouseEventDemo panel. If you add this applet to a web page, your program will be running in a rectangular area on the page. The mosaic draw program that you wrote for Assignment 2 works in a similar way; that is, it can be used either in the stand-alone application defined by the file MosaicDraw.java, or it can be used in the applet defined by MosaicDrawApplet.java. Several of the remaining labs in the course will follow a similar pattern.

As part of your work for this lab, you will start posting some of your work on the Web as applets. You can publish something on the web simply by placing it in the www directory in your home directory. To get you started, there is a small sample web site that you should copy into your www directory. (If you had previously created a cs124 directory in your www directory, consult with me about what to do.) You can do this in one of two ways:

  • Using the GUI, open two directory windows. Navigate in one to your www directory. Navigate in the other to the directory /classes/f05/cs124/lab9. Drag the folder named cs124 from /classes/f05/cs124/lab9 to your www directory. When you release the mouse, you will be asked whether you want to copy, move, or link the folder; say that you want to copy it.

  • Open a console window and use the command  cp  -r  /classes/f05/cs124/lab9/cs124  www  to copy the whole cs124 directory into your www directory.

    Once you do this, the web site will be visible at the web address http://math.hws.edu/~xx9999, with xx9999 replaced by your own two-letter-plus-four-digit username. (You could also install the Web site by downloading this zip file.)

    Unfortunately, the applets that you write in this course require Java 1.5 or higher. Not everyone has Java on their computer, and not everyone who has it has a new enough version. So, not everyone who visits your web site will be able to see your applets. When Java was introduced, applets were considered to be an important part of the language, but since then, support for applets and interest in them has waned and Java applications have become more important. It's still nice, though, to be able to put your work on the Web for those who can see it.

    The structure of your web site was cribbed from my About Linux site. It uses an HTML feature known as "frames" which allows several HTML source files to be shown in different areas of the screen. The blue menu strip down the left side of the page is one example of this; the content of this side of the page is defined by the file menu.html. The largest part of the page is occupied by the file main.html when you first open the site. However, clicking on the MouseEvents link in the menu strip will replace the page with MouseEvents.html, which displays the original MouseEventsDemo program as it was before you started working on it. To add a new applet to the site, you will have to create a new web page to display the applet, and you will have to edit the menu.html file to add a link to the new page.

    The first thing that you will want to do is to replace the old MouseEventDemo applet with your own work. To do this, you should export your work from Eclipse as a jar file. That is:

    1. Select the three files MouseEventsDemo.java, MouseEventsApplet.java, and MouseEventsApplication.java in the area on the left end of the Eclipse window.
    2. Right-click the file, and select "Export...".
    3. Select "Jar File" and click "Next".
    4. Set the export destination for the .jar file to /home/xx9999/www/cs124/MouseEventsDemo.jar but replacing xx9999 with your own user name.
    5. Click "Next" twice. Set "MouseEventsApplication" as the main class for the .jar file. This is not necessary for the applet, but doing this will allow you to run the .jar file as an application.
    6. Click "Finish". You will have to confirm that you want to replace the existing MouseEventsDemo.jar.

    This will save the .jar file directly into your web site folder, so your own version of the applet will appear on the web page. (You might have to reload the page.)

    You will also need to edit the file MouseEvents.html so that it properly describes what your applet does. And you will want to edit the introductory page, main.html, to add a brief description of what the web site is about and perhaps a few words about yourself.

    You will want to add additional applets to your site. You might be required to do so in future labs. For the time being, you should add an applet version of the MosaicDraw program from Assignment 2 to your site. Here is how to do this:

    1. Copy the file MouseEvents.html to create a duplicate file named MosaicDraw.html. (The name could be anything, but I will assume that this is what you call it.)
    2. Edit the file menu.html to add a link to MosaicDraw.html. The link will look like the link to MouseEvents.html:
            <p><a href="MosaicDraw.html" target="mainframe">Mosaic Draw</a></p>
    3. Create a .jar file containing all the classes from the Mosaic Draw project. Let's say that you call it MosaicDraw.jar. Put this jar file into your web site folder.
    4. Edit the new html file, MosaicDraw.html so that it shows the mosaic draw applet instead of the mouse events applet. Since MosaicDrawApplet is defined in a package named mosaic_draw, the code location for the applet has to include the name of the package. The <applet> tag should be changed to look something like this:
           <p align=center>
           <applet code="mosaic_draw.MosaicDrawApplet.class" 
                              archive="MosaicDraw.jar" width=500 height=530>
    5. Edit the text in the MosaicDraw.html file to describe the applet.

    The Mosaic Draw applet should now be available on your web site. Again, you might have to reload the page to see the new link that you have added.

    Remember that if you need help with any of this, you should visit my office to get it. Also, you might want to consult with me about other changes you could make to the site, such as using a different graphic as a title.

    Exercise 2: Create a cs124 web site in your www directory, as described above. Your web site should have an introductory page, the MouseEventsDemo applet that you wrote for this lab, and the MosaicDrawApplet from Assignment 2. You can also add the RandomArt applet from Lab 5, if you want. Remember that you need to edit the introductory page, main.html, to personalize your site and to provide more information about it, and you need to edit the file MouseEvents.html to give correct information about what the applet does.

    David J. Eck, October 2005