11. More about methods

Whenever you were compiling a program that makes use of the method action, you may have noticed that Java issued a warning. The method action (and a few other methods) are not up-to-date anymore and have been replaced by methods (the so-called Listener methods) that work more efficiently.

These newer methods are part of so-called interfaces. But what is an interface?

Every applet we made so far started like this:

public class SoAndSo extends Applet {
The addition extends Applet means that this program inherits all functionality from the class Applet. One of the consequences of this inheritance is that applets 'know' how to deal with methods such as init and paint. Unfortunately, classes cannot inherit from more classes than one.

Just like inheritance (via extends), an interface makes it possible to give additional functionality to a program. But if we compare it to inheritance, the inclusion of an interface has one important advantage and one drawback:
  • An advantage is that our applets (and all other classes) can inherit from more interfaces than one.
  • A disadvantage is that all methods that are part of the interface must be included.
The interface ActionListener
In the applets we made so far, you may have noticed that, unless a button was clicked, no use could be made of text typed into a textfield. It would be more pleasant if we could just press the Enter key.

We can bring this about with the interface ActionListener. For this, we have to add four lines to our program:
  1. at the start, include an extra package with:
  2. import java.awt.event.*;
  3. in the first line we must make it clear that an interface is being used with:
  4. ... implements ActionListener
  5. the interface must be linked to the textfield in the method init:
  6. box.addActionListener (this);
  7. all methods must be included. Fortunately, this interface has only one method:
  8. public void actionPerformed (ActionEvent ae)
A simple demonstration how this interface is used can be seen in the following program, which makes use of a self-made method (of the String type), which "inverts" a word.
// Simple demonstration of the interface ActionListener
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class WordInverter extends Applet
                                            implements ActionListener {

TextField box = new TextField(20);
String word1 = "Type a word and press <Enter>";
String word2 = "";

public void init () {
     add (box);
     vak.addActionListener (this);
}

public void paint (Graphics g) {
     g.drawString (word1, 20, 120);
     g.drawString (word2, 20, 160);
     box.requestFocus();
}

public void actionPerformed (ActionEvent ae) {
     String typed = box.getText();
     word1 = "You typed: " + typed;
     word2 = "Inverted: " + invert (typed);
     box.setText("");
     repaint();
}

String invert (String s) {
     String temp = "";
     for (int i=s.length()-1; i>=0; i--)
          temp += s.charAt (i);
     return temp;
}

}
 

             


MouseListener
A second series of Listener-methods is found in the interface MouseListener. Just like any other interface, this one is added in four steps:

  1. include the package java.awt.event with:
  2. import java.awt.event.*;
  3. actually add the interface to the program with:
  4. . . .  implements MouseListener
  5. add the interface to the applet (in init) with:
  6. addMouseListener (this);
  7. this interface has five methods, which must all be included, whether we use them or not:
  8. public void mouseClicked (MouseEvent evt) { }
    public void mousePressed (MouseEvent evt) { }
    public void mouseReleased (MouseEvent evt) { }
    public void mouseEntered (MouseEvent evt) { }
    public void mouseExited (MouseEvent evt) { }
The methods introduced in this chapter will be demonstrated in a program which will allow us to draw triangles by clicking the mouse. 

In order to clear the window, we'll add a button which will carry out a complete repaint.

But the triangles we've drawn may not be erased. So we can't just use a repaint - or we would draw only one triangle at a time. We are going to solve this problem by "overriding" the mechanism that actually draws the applet. Overriding means we are not going to use the standard mechanism, but we'll replace it with a method of our own.

The actual drawing in an applet is normally done by a method called update. This method starts by drawing a new background to the applet window, which means the window is actually erased. Then paint is invoked, which carries out the actual drawing.

We can, however, override this method by writing our own version of update, which allows paint to draw, but does not erase anything. This can be done quite simply, for instance like this:
public void update (Graphics g) {
    paint (g);
}
An important aspect of computer programs that interact with people is feedback. Humans appreciate it when a program responds to what they do. After all, when it's people we communicate with, don't we also expect them to respond?

In order to supply this feedback, we'll mark the spots that have been clicked on, with dots. The coordinates of these dots can be found by the method mouseClicked:
public void mouseClicked (MouseEvent evt) {
     x [turn] = evt.getX ( );
     y [turn] = evt.getY ( );
     turn ++;
     update (getGraphics());
}
You see: the co-ordinates are stored in two arrays (x[ ] and y[ ]), which have been defined like this:
int x[ ] = new int [3], y[ ] = new int [3];
int turn = 0;
As the variabele turn gets the values 0, 1 and 2, the method mouseClicked will neatly capture three sets of co-ordinates. As soon as the reset button (included in this applet) is clicked, the window is wiped clean by filling it with a white rectangle.

If not, a dot is painted at the point that's been clicked. At the third point, a new triangle is drawn by the method triangle, like this:
if (reset) {
     g.setColor (Color.white);
     g.fillRect (0,0,getSize().width,getSize().height);
     reset = false;
     g.setColor (Color.black);
}
else {
     if (turn>0)
          g.drawOval (x[turn-1], y[turn-1],1,1);
     if (turn==3) {
          triangle (g,x[0],y[0],x[1],y[1],x[2],y[2]);
          turn = 0;
     }
}
The rest of the program will probably be not too difficult to understand:
// Drawing triangles
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DrawTriangle extends Applet
implements ActionListener, MouseListener {
int x[]=new int[3], y[]=new int[3], turn = 0;
Button button = new Button ("new");
boolean reset;

public void init () {      
     addMouseListener (this);
     add (button);
     knop.addActionListener (this);
}

public void paint (Graphics g) {
     if (reset) {
          g.setColor (Color.white);
          g.fillRect (0,0,getSize().width,getSize().height);
          reset = false;
          g.setColor (Color.black);
     }
     else {
          if (turn>0)
          g.drawOval (x[turn-1], y[turn-1],1,1);
          if (turn==3) {
                triangle (g,x[0],y[0],x[1],y[1],x[2],y[2]);
                turn = 0;
          }
     }
}

public void triangle (Graphics g, int x1, int y1,
     int x2, int y2, int x3, int y3) {
     g.drawLine (x1, y1, x2, y2);
     g.drawLine (x2, y2, x3, y3);
     g.drawLine (x3, y3, x1, y1);
}

public void mouseClicked (MouseEvent evt) {
     x[turn] = evt.getX();
     y[turn] = evt.getY();
     turn++;
     update(getGraphics());
}


public void mousePressed (MouseEvent evt) {}
public void mouseReleased (MouseEvent evt) {}
public void mouseEntered (MouseEvent evt) {}
public void mouseExited (MouseEvent evt) {}

public void update(Graphics g) {
     paint (g);
}

public void actionPerformed (ActionEvent ae) {
     turn = 0;
     reset = true;
     update(getGraphics());
}
}

A working specimen can be seen here:

                 

Exercise 11.1
Write an applet in which a sentence can be typed into a textfield. After pressing the enter key, the texfield is cleared and the sentence is shown again. And the applet informs us how many vowels (a, e, i, o, u, including the capitals) the sentence contains. The counting should be done in a separate method, which returns the number of vowels.

                  

Exercise 11.2
Write an applet in which a piece of line is drawn every time the mouse is clicked. The line starts at the last line drawn and goes as far as the point which is clicked. The drawing should start at the top left hand corner, where there is a small rectangle where we see the word "reset". Clicking this last rectangle will erase the old lines and start a new set.

                 

Chapter 12

Menu Java Tutorial

home page

(c) 2005, Thomas J.H. Luif