Java Programming   Java Programming
 |Sofia Home | Content Gallery |
Home
Syllabus
Schedule
Lessons
Assignments
Resources

Lesson 2.5 Talking to Objects

Talking To Objects

You communicate with objects by sending them messages. To see how this works, we'll take the FirstApplet program and send a message to the Label field named theLabel .

import java.awt.*;
import java.applet.*;
public class FirstApplet extends Applet
{
   // Attributes go here
   Label theLabel = new Label("Hi Mom!");

   // Methods go here
   public void init()
   {
      add(theLabel);
   }
}

Let's tell it to change the words that are displayed, from "Hi Mom" to "Hi Mom & Dad."

Sending a Message

The FirstApplet class only has a single method, init() and since methods are the only place where any action occurs, we'll have to send our message inside the init() method.
Who?
When you send a message to an object, that object is called the receiver of the message. Whenever you send a message, you start by specifying the receiver, like this:
 
public void init()
{
   theLabel
   add(theLabel);
}
What?
After you've specified the receiver of the message, you have to tell the object what you want it to do. You do that by using the name of the message, [this is called the request], followed by parentheses.
Separate the name of the message from the receiver of the message with a single period (.)
.

To find out the name of the message, you'll have to look through the JavaDoc documentation. (Lesson 2.6 shows you how to read the JavaDoc documentation.)
After perusing the JavaDoc Label class, you see that there is a method called setText() that allows you to change the text of a label, so you can write this:

public void init()
{
   theLabel.setText();
   add(theLabel);
}
What Else?
Whenever you send a message to an object, frequently the object will require additional information before it can carry out your request. This additional information is specified in the Java documentation as the method's argument or arguments. 

If you look at the documentation for the setText() method, you'll see that it requires a String argument. We haven't yet formally met the String class, so for right now let's think of it as "text between double-quotes".

All of this makes perfect sense, of course. You told the Label object named theLabel to change the text it displayed, but then you didn't tell it what new and different text you wanted displayed. No wonder it got annoyed!

Simply change your code like this and everything will compile and work as expected. (Don't forget the closing quotes, however).

public void init()
{
   theLabel.setText("Hi Mom & Dad");
   add(theLabel);
}
Back to Top

A Second Message

Let's do one more quick example that's a little more complex. Let's send a message to theLabel and tell it to use a different font.

Finding the Info

If you look in the JavaDocs under the Label class, you'll see that there are only six methods, and nothing that lets you change a font! The secret however, is in knowing where to look. 

Because the Label class extends the Component class, just like your FirstApplet class extends Applet, it inherits all of the methods that the Component class has. And, if you go looking through the Component class you'll find a method that looks like this:

setFont(Font);

Now all we have to do is find out how to create a Font object.

We already know how to create a Font object. We'll just use the Font constructor, whose name is...you guessed it, Font(). When we look it up in the documentation, we see that there is a Font() constructor that requires three arguments in this order:

  • Name: This should be a string that contains "Courier", "Helvetica", "TimesRoman", etc. With Navigator, you can also use "Serif," "SansSerif," or "Monospaced." These are the platform-independent logical fonts that will be replaced with Arial or Helvetica or New Times Roman, etc. depending upon the platform the application runs on. Unfortunately, the platform-independent fonts don't seem to work with Internet Explorer, so you should probably use the original names.
  • Style: This is a combination of variables defined inside the Font class. You can use Font.PLAIN, Font.BOLD, Font.ITALIC, or Font.BOLD + Font.ITALIC. Using something like Font.PLAIN + Font.BOLD doesn't make any sense, but it won't create a syntax error. Make sure you get the capitalization right on these.
  • Size: The size of a Font is measured in points. There are 72 points to an inch. Normal body text is usually 10 or 12 points.

Note: Make sure you don't accidentally transpose the Style and Size arguments. That won't create a syntax error, but it does result in a font that is too small to see.

Back to Top

Sending the Message

Before you can send theLabel a setFont() message, you first have to create a Font object. You do that just like you would any other field.
 
Font bigFont = 
     new Font( “Serif”, Font.PLAIN, 36);

Once you've done that, you can tell theLabel to use a different font just like this:

theLabel.setFont(bigFont);
Back to Top

Events

While messages allow you to communicate with your objects, they don't allow your objects to "talk back." Events change that. 

Events are external occurances that let you know something has happened in your program. Usually an event is triggered by a user interacting with your progam. When the user clicks on a button, for instance, events allow the Button object to notify you that this has occurred.

Java has two different schemes for dealing with events. The first scheme, introduced in Java 1.0, is like a broadcast model. When the user clicks on a button under the Java 1.0 model, the button notifies everyone in its immediate vicinity that "Hey! I've been clicked."

This scheme works well for very simple applets and it is still the only scheme that is supported under some Web browsers. Nevertheless, it has some obvious failings. If you create an applet that has several buttons, for instance, each of them will be shouting "Look at me! I've been clicked." This leaves it up to the applet to sort out which button was clicked and what to do about it. Besides, it makes for a noisy, unpleasant environment.

In the Java 1.1 event model, which has been carried through into Java 2, objects have to subscribe to a component's events. For instance, if I want my applet to do something when a particular button is pressed, I have to explicitly tell that button "Notify me when something happens." If I don't ask the button to notify me, it will keep the information to itself. This makes for a much more orderly and efficient working environment.

Back to Top

Working with Java 1.1 Events

To use events under Java 1.1 is a three-step process:
  • Prepare to accept event messages
  • Start listening for events
  • Respond to event messages when they appear
Let's walk through each of these steps. We'll have in FirstApplet class respond to moving the mouse over our applet.
Step 1: Preparation
There are two things we have to change to FirstApplet before we can use Java 1.1 events. We have to begin by importing the package that contains the event code: java.awt.event. Then, we have to add a new phrase to the class header:
implements MouseMotionListener
When we're done, FirstApplet should look like this:
 
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class FirstApplet extends Applet
       implements MouseMotionListener
{
   // Attributes go here
   Label theLabel = new Label("Hi Mom!");

   // Methods go here
   public void init()
   {
      add(theLabel);
   }
}

Step 2: Subscribing
You subscribe to a particular event by telling the object that generates events [in this case theLabel] that you want it to add you to its "list of subscribers." This list of subscribers is called a "listener list", and there's a special method to sign up for each of the events that a component can generate. 

The method to sign up for mouse motion events is called addMouseMotionListener(). Send this message to your Label object, theLabel, and pass along the special argument this. Passing this as an argument tells theLabel “Send the MouseEvent object to me. (that is, the Applet itself.)”

The revised FirstApplet applet should look like this:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class FirstApplet extends Applet
       implements MouseMotionListener
{
   // Attributes go here
   Label theLabel = new Label("Hi Mom!");

   // Methods go here
   public void init()
   {
      theLabel.addMouseMotionListener(this);
      add(theLabel);
   }
}

Step 3: Responding to Events
Now that theLabel is prepared to notify you (or your applet) whenever a MouseEvent occurs in its neighborhood, you need to be prepared to respond. You respond to events by writing methods.

What methods should you write? Different “event packages” require you to write different methods. To subscribe to MouseMotionListener you have to add two new methods to your class:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class FirstApplet extends Applet
             implements MouseMotionListener
{
   // Attributes go here
   Label theLabel = new Label("Hi Mom!");

   // Methods go here
   public void init()
   {
      theLabel.addMouseMotionListener(this);
      add(theLabel);
   }

   // New methods here
   public void mouseMoved( MouseEvent  e )
   {
      // Add statements here
   }

   public void mouseDragged( MouseEvent e )
   {
      // Add statements here
   }
}

Add these two methods inside your class. It is not important which one goes first, but you must make sure that they appear inside the braces that delimit the FirstApplet class body, but not inside another method such as init().

Back to Top

What Should You Do?

Now, when the user moves the mouse over theLabel, theLabel will notify your applet by calling the applet's mouseMoved() method. Similarly, if the user drags the mouse [moving and holding down the primary mouse button] over theLabel, it will notify your applet by calling its mouseDragged() method. 

What happens if the user clicks the mouse while over theLabel? Nothing. The Label object is "aware" that the event has occurred, but because no one has subscribed to the MouseListener [different than MouseMotionListener], it keeps the information to itself.

When theLabel calls your mouseMoved() or MouseDragged() method, it passes along a reference to the MouseEvent object that triggered all the fuss. You can send messages to the MouseEvent object [here we've named it e] to find out what it's up to.

Two of the MouseEvent messages you might find most useful are getX() and getY() which return the horizontal and vertical mouse coordinates [starting at 0,0 in the upper-left corner of the component generating the event, and increasing right and down] when the MouseEvent occurred.

If you want to receive a message whenever the mouse is moved outside of the area occupied by your Label object, locate the line that sends the addMouseMotionListener() message to theLabel , and remove the reference to theLabel from the front, so it just reads addMouseMotionListener(this);. The applet will then notify you when the mouse is moved outside of the area occupied by your label.

Once you've done that, you can use this information to change the behavior of your Label object, theLabel, by sending theLabel the setLocation() message, and passing this information along as the argument like this:

theLabel.setLocation(e.getX(), e.getY());

This causes theLabel to move its upper-left corner wherever the mouse appears, essentially following the mouse around the applet.

Other messages you might like to send to theLabel include setBackground(), setForground(), setBounds() ,...

Well, you get the idea. The rest is up to your imagination.

Something to Talk About

Using the code for the FirstApplet class shown earlier in this page under the subhead Step 2:Subscribing, try to change the code so that theLabel will "run away" from the mouse instead of follow it around. Can you do it?

Please continue to the next section of this lesson.

 

Back to Top
Content Developed by Stephen Gilbert, Licensed under a Creative Commons License
Published by the Sofia Open Content Initiative
© 2004 Foothill-De Anza Community College District &The William and Flora Hewlett Foundation