Turtlegraphics for Smartphones and Tablets

Bern University of Teacher Education  
HomeStart Online EditorPrintAndroid GamesJava-Online

Touch-Events


To create interactive apps that react to display touches is one of the most important program techniques when programming smartphones and tablets. In the class library JTurtleLib TouchEvents are implementable with simple methods. Their usage is presented with examples.

In the first example we use the method playgroundPressed(x,  y). This method is called by the system when touching the screen and gives the coordination of the touching point. The x-coordinate can accept values from -200 to 200, from left to right, y can accept values from -200 to 200 down to up. The coordinating system is independent from the sceen resolution of the machine.

Our example is a nice use of the object oriented programming. With the method playgroundPressed() a turtle joe, that draws a star, is created. By touching the display a new turtle appears. Because the method playgroundPressed() is called in independent threads, all turtles draw stars together.

Edit source with online-compiler

install App on smartphone or tablet

QR-Code

download sources (Tu16.zip)

// Tu16java

package app.tu16;

import turtle.*;

public class Tu16 extends Playground
{
  public void playgroundPressed(double x, double y)
  {
    Turtle joe = new Turtle(x, y);
    for (int = 0; i < 6; i++)
    {
      joe.fd(20);
      joe.rt(140);
      joe.fd(20);
      joe.lt(80);
    }
  }
}

 

Explanations to the program code:

public void playgroundPressed(double x, double y)

The method has to be public in order to be visible for the Android-system.
Instead of playgroudPressed() also the method playgroundClicked(), which reacts on pressing and releasing, can be used.

main() main() is not necessary, because it is an event-controlled program.

 

Drawing connecting lines from touch to touch. At the beginning turtle joe is in the middle of the playgrounds. With every touch of the display, the connecting line is drawn from the old to the new position.

Edit source with online-compiler

install App on smartphone or tablet

QR-Code

download sources (Tu17.zip)

// Tu17.java

package app.tu17;

import turtle.*;

public class Tu17 extends Playground
{
  public void main()
  {   
    st();
    setColor(RED);
    setSpeed(MAXSPEED);
  }
  
  public void playgroundPressed(double x, double y)
  {
    joe.moveTo(x, y);
  }
}

 

Explanations to the program code

moveTo(x, y)

Is the turtle moving from the current position to the point with the coordinates x, y, in our case to the touching point, and draws in contrast to setPos(x, y) a trace