Turtle Graphics with Java

Bern University of Teacher Education  
HomeStart Online-EditorPrintAndroid-TurtlegraphicsJava-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.

Run this example (Tu26.java)

// Tu26.java
// Key Event: the turtle can be moved using the arrow keys

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

class Tu26 extends Turtle
{
  
  Tu26()
  {
    setFontSize(10);
    setPos(-180180);
    label("Use cursor keys to move me!");
    home();
    
    addKeyListener(new KeyAdapter()
    {
      public void keyPressed(KeyEvent evt)
      {
        int step = 10;
        int keyCode = evt.getKeyCode();
        switch (keyCode)
        {
          case KeyEvent.VK_LEFT :
            setHeading(-90);
            forward(step);
            break;

          case KeyEvent.VK_RIGHT :
            setHeading(90);
            forward(step);
            break;

          case KeyEvent.VK_UP :
            setHeading(0);
            forward(step);
            break;

          case KeyEvent.VK_DOWN :
            setHeading(180);
            forward(step);
            break;
        }
      }
    });
  }

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

Test this example in the Online-Editor

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.

Run this example (Tu27.java)

// Tu27.java
// Moves the Turtle to the cursor position

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

class Tu27 extends Turtle
{

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

    hideTurtle();
    setColor(Color.red);
    setFontSize(10);
    setPos(-180180);
    label("Use mouse clicks to make me jump!");
    home();
    showTurtle();
  }

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

Test this example in the Online-Editor

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.

Run this example (Tu28.java)

// Tu28.java
// Draws lines between the old and the new position

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

class Tu28 extends Turtle
{
  private Point2D.Double pEnd;
  private double d;
  
  Tu28()
  {
    addMouseListener(new MouseAdapter()
    {
      public void mousePressed(MouseEvent e)
      {
        pEnd = toTurtlePos(e.getPoint());
        d = distance(pEnd);
        double w = towards(pEnd);
        heading(w);
        forward(d);
      }
    });

    hideTurtle();
    setColor(Color.red);
    setFontSize(10);
    setPos(-180180);
    label("Use mouse clicks to move the turtle and paint!");
    home();
    showTurtle();
  }

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

Test this example in the Online-Editor

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.

Run this example (Tu29.java)

// Tu29.java
// The squares of the chessboard can be colored by clicking on them

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

class Tu29 extends Turtle
{
  private Point2D.Double pFill;
  private double x, y;
  
  Tu29()
  {
    hideTurtle();
    
    for (= -180; x < 190; x = x + 40)
    {
      setPos(x, -180);
      forward(360)
    }
    
    right(90);
    
    for (= -180; y < 190; y = y + 40)
    {
      setPos(-180, y);
      forward(360)
    }
    
    addMouseListener(new MouseAdapter()
    {
      public void mousePressed(MouseEvent e)
      {
        setScreenPos(e.getPoint());
        fill();
      }
    });

    setFontSize(10);
    setPos(-180185);
    label("Use mouse clicks to fill some fields!");
  }

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

Test this example in the Online-Editor

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.

Run this example (Tu30.java)

// Tu30.java
// left mouse click moves joe, right mouse click moves lea

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

class Tu30
{
  private Turtle joe = new Turtle();
  private Turtle lea = new Turtle(joe);
  private Point2D.Double pEnd;
  private double d, w;

  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.setPos(-180180);
    joe.setFontSize(10);
    joe.label("Use left click to move red turtle, 
               right click to move blue turtle!"
);
    joe.setColor(Color.red);
    joe.setPenColor(Color.red);
    joe.setPos(-400);
    lea.setPos(400);
  }
  
  void draw(Turtle t)
  {
    d = t.distance(pEnd);
    w = t.towards(pEnd);
    t.heading(w);
    t.forward(d);
  }
  
  public static void main(String[] args)
  {
    new Tu30();
  }
}
   

Test this example in the Online-Editor

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!

Run example (Tu31.java)

// Tu31.java
// Freehand drawing with a pressed mouse button

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

class Tu31 extends Turtle
{
  private Point2D.Double pEnd;
  private double d;
  
  Tu31()
  {
    addMouseListener(new MouseAdapter()
    {
      public void mousePressed(MouseEvent e)
      {
        pEnd = toTurtlePos(e.getPoint());
        d = distance(pEnd);        
        double w = towards(pEnd);
        heading(w);
        penUp();
        forward(d);
        penDown();
      }
    });
    
    addMouseMotionListener(new MouseMotionAdapter()
    {
      public void mouseDragged(MouseEvent e)
      {
        pEnd = toTurtlePos(e.getPoint());
        d = distance(pEnd);        
        double w = towards(pEnd);
        heading(w);
        forward(d);
       }
    });

    hideTurtle();
    setColor(Color.red);
    setFontSize(10);
    setPos(-180180);
    label("Take turtle to paint!");
    setPenColor(Color.red);
    home();
    showTurtle();
  }

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

Test this example in the Online-Editor


Exercises