Turtlegraphics with Java
HomeAufgabenDruckenJava-Online

Events

Applications using graphical user interfaces (GUI) are often controlled through events. Each user action with the mouse or the keyboard provokes an event. To use event-controlled program it is necessary to write an adapter class which implements a listener interface. This class contains methods which are called automatically when en event is provoked. These methods are called callback methods. To activate the events it is necessary to register a instance of the adapter class with the method addListener().
This tutorial limits itself to some examples that can easily be adapted to other situations.


Keyboard events

If keyboard events need to be caught a class KeyAdapter needs to be written. It contains the method keyPressed(), which is called when a key is pressed on the keyboard. To find out exactly which key was pressed the method getKeyCode() is necessary. To activate the keyboard events in a Turtle window the adapter must be registered with the method addKeyListener().

In the next example the Turtle can be moved using the arrow keys.

// Tu26.java

import ch.aplu.turtle.*;
import java.awt.Color;

public class Tu26
{
  private class MyMouseHitListener implements MouseHitListener
  {
    public void mouseHit(double x, double y)
    {
      Turtle = new Turtle(tf);
      t.setPos(x, y);
      draw(t);
    }
  }

  TurtleFrame tf = new TurtleFrame();

  private Tu26()
  {
    tf.addMouseHitListener(new MyMouseHitListener());
    tf.addStatusBar(20);
    tf.setStatusText("Click to create a new turtle!");
  }

  private void draw(Turtle t)
  {
    int = (int)(Math.random() * + 2);
    for (int = 0; i < 60; i++)
      t.forward(a).right(6);
  }

  public static void main(String[] args)
  {
    new Tu26();
  }
}
   

Explaining the program code:
import java.awt.event.*;
This imports the class library event, which provides the event-methods
void keyPressed(KeyEvent evt) This method is automatically executed when a key is pressed
int keyCode = evt.getKeyCode(); The code of the pressed key is saved in the variable keyCode
VK_LEFT, VK_DOWN Some special keys, such as the arrow keys, the enter or delete key, are defined as virtual keys in the method getKeyCode(). Working with the other keys it is necessary to know its numerical code.


Mouse events

Using mouse events mouse-controlled actions can be caught. The mouse is watched inside the graphical window with the help of the MouseListener and the MouseMotionListener. The MouseListener reacts to the mouse buttons and the MouseMotionListener can register the cursor movements.

Example 1: If a mouse button is clicked, the Turtle is moved to the cursor position.


// Tu27.java

import ch.aplu.turtle.*;
import java.awt.Color;
import java.awt.event.*;

public class Tu27 extends Turtle
{

  public Tu27()
  {
    addMouseListener(new MouseAdapter()
    {
      public void mousePressed(MouseEvent e)
      {
        setScreenPos(e.getPoint());
      }
    });

    setColor(Color.red);
    addStatusBar(20);
    setStatusText("Click to move the turtle!");
  }

  public static void main(String[] args)
  {
    new Tu27();
  }
}
   

Explaining the program code:
void mousePressed(MouseEvent e)
This method is automatically called when the mouse button is clicked
e.getPoint() Gets the cursor position
setScreenPos(e.getPoint()) Moves the Turtle to the cursor position

 

Example 2: When clicking the Turtle is moved to the cursor position and a line is drawn between the old and the new position.

// Tu28.java

import ch.aplu.turtle.*;
import java.awt.Color;
import java.awt.event.*;

public class Tu28 extends Turtle
{
  public Tu28()
  {
    fillToPoint(0, 0);
    hideTurtle();
    addMouseListener(new MouseAdapter()
    {
      public void mousePressed(MouseEvent e)
      {
        double = toTurtleX(e.getX());
        double = toTurtleY(e.getY());
        double = distance(x, y);
        double = towards(x, y);
        heading(w);
        setPenColor(new Color((int)(Math.random() * 255),
                     (int)(Math.random() *255), 255));
        forward(d);
      }
    });

    addStatusBar(20);
    setStatusText("Click and create a picture!");
  }

  public static void main(String[] args)
  {
    new Tu28();
  }
}
   

Explaining the program code:
pEnd = toTurtlePos(e.getPoint());
Saves the new position of the Turtle in the variable pEnd
d = distance(pEnd); Calculates the distance between the current and the old position of the Turtle
double w = towards(pEnd);
.heading(w);
Calculates the direction towards the mouse click and turns the Turtle in this angle


Example 3: The squares of a chessboard can be colored by clicking on them.


// Tu29.java

import ch.aplu.turtle.*;
import java.awt.event.*;
import java.awt.geom.*;


public class Tu29 extends Turtle
{
  private Point2D.Double pFill;

  public Tu29()
  {
    hideTurtle();

    for (int = -180; x < 190; x = + 40)
    {
      setPos(x, -180);
      forward(360);
    }
    right(90);
    for (int = -180; y < 190; y = + 40)
    {
      setPos(-180, y);
      forward(360);
    }

    addMouseListener(new MouseAdapter()
    {
      public void mousePressed(MouseEvent e)
      {
        setScreenPos(e.getPoint());
        if (getPixelColorStr(== "white")
          fill();
      }
    });

    addStatusBar(20);
    setStatusText("Click to fill some fields!");
  }

  public static void main(String[] args)
  {
    new Tu29();
  }
}
   

Explaining the program code:
setScreenPos(e.getPoint());
fill();
The Turtle is moved to the position of the click and the surrounding square is filled.

 

Example 4: Click the left mouse button to move the red Turtle and the right to move the blue Turtle.


// Tu30.java

import ch.aplu.turtle.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;

public class Tu30
{
  private Turtle joe = new Turtle();
  private Turtle lea = new Turtle(joe);
  private Point2D.Double pEnd;

  public Tu30()
  {
    joe.addMouseListener(new MouseAdapter()
    {
      public void mousePressed(MouseEvent e)
      {

        if (SwingUtilities.isLeftMouseButton(e))
        {
          pEnd = joe.toTurtlePos(e.getPoint());
          draw(joe);
        }

        if (SwingUtilities.isRightMouseButton(e))
        {
          pEnd = lea.toTurtlePos(e.getPoint());
          draw(lea);
        }
      }
    });

    joe.addStatusBar(20);
    joe.setStatusText("Use left click to move red turtle, 
                       right click to move blue turtle!");
    joe.setColor(Color.red);
    joe.setPenColor(Color.red);
    joe.setPos(-40, 0);
    lea.setPos(40, 0);
  }

  private void draw(Turtle t)
  {
    double = t.distance(pEnd);
    double = t.towards(pEnd);
    t.heading(w);
    t.forward(d);
  }

  public static void main(String[] args)
  {
    new Tu30();
  }
}
   

Explaining the program code:
if (SwingUtilities.isLeftMouseButton(e)) Checks if the left mouse button was clicked.
if (SwingUtilities.isRightMouseButton(e)) Checks if the right mouse button was clicked.

 

Example 5: Freehand drawing with a pressed mouse button. Click on the Turtle and start drawing!


// Tu31.java

import ch.aplu.turtle.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class Tu31 extends Turtle
{
  private Point2D.Double pEnd;

  public Tu31()
  {
    addMouseListener(new MouseAdapter()
    {
      public void mousePressed(MouseEvent e)
      {
        setScreenPos(e.getPoint());
      }
    });

    addMouseMotionListener(new MouseMotionAdapter()
    {
      public void mouseDragged(MouseEvent e)
      {
        pEnd = toTurtlePos(e.getPoint());
        double = distance(pEnd);
        double = towards(pEnd);
        heading(w);
        forward(d);
       }
    });

    speed(-1);
    setColor(Color.red);
    setPenColor(Color.red);
    addStatusBar(20);
    setStatusText("Drag turtle to paint!");
  }

  public static void main(String[] args)
  {
    new Tu31();
  }
}