Prev Up Next
Go backward to Writing (and Running) Your First Applet
Go up to Top
Go forward to Tracking Mouse Movement

Variations on a Theme

To get more comfortable working with Metrowerks, you should now experiment with some variations on the instructions placed in the methods of your applet. As a start, we will make the applet a bit more aware of the mouse's activities.

As written, the "mouseDown" method always draws its message in the middle of the screen. A slight change will make it draw the message where the mouse was clicked.

The pixels on a computer's screen can be identified precisely using a cartesian coordinate system. That is, we can associate x and y coordinates with each point on the screen. When the mouse button is pressed, the computer is willing to provide the coordinates of the pixel the mouse was pointing at to the method that responds to the button press. To use these values, the method just needs to tell the computer what names it would like associated with these numbers. This is done by adding "parameter declarations" to the method specification.

To add and then use parameters to the "mouseDown" method:

Now, we can use the names "x" and "y" to refer to the coordinates where the mouse is clicked. To do this:

This actually illustrates an important property of Java. There are many parameters that can be included to control the details of how a string is drawn using the "drawString" primitive. You must, of course, specify the message. In the original version of mouseDown that was all we specified. If you wish, you can also specify a position at which to draw, and, as we will see later, a color to use. If any of these extra details are not included, suitable defaults are used. If the position is not specified, the text is centered in the applet's region of the screen. If no color is specified, black is used.

Now, run your applet again (select "Run" from the "Project" menu). If you made any typing mistakes, a window of complaints from Metrowerks about the grammar of your applet will appear instead of the "AppletViewer" windows. If you can identify the problem, edit the text to correct it and select "Run" again. If you have trouble spotting the mistake, ask your TA or instructor. Once the "Run" succeeds, click the mouse within the "AppletViewer" window to see the difference between this applet and the original. When you are done be sure to "Quit" the AppletViewer. Don't just click on the editor window to bring it to the foreground. If you do, windows corresponding to all the runs of your applet will pile up on your screen.

Now, let's move some of the commands in the applet around rather than modifying them.

Before you proceed, take a moment to try to predict how the computer will behave when obeying these modified instructions. Then, select "Run" again and see what actually happens. Were you able to predict in? Once you have given the applet a try, select "Quit" to get back to the editor.


Prev Up Next