Hello, I am a beginner in Greenfoot and i have trouble with understanding how to manage the keyboard.
My problem is: I have a class TestWorld with an actor Texto. What iI want is showing in Texto the key that has been pressed (whatever key). How can I detetect that a key has been pressed? And wich is the best act() method to put it this code, in act() of testWorld or in act() of Texto.
This is my code:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
/**
*
*/
public class TestTeclado extends World
{
private Texto texto;
/**
* Constructor para objetos de clase TestTeclado.
*
*/
public TestTeclado()
{
// Crea un nuevo mundo de 600x400 celdas con un tama�o de celda de 1x1 pixeles.
super(600, 400, 1);
GreenfootImage bg = getBackground();
bg.setColor(Color.BLACK);
bg.fill();
inicializar();
}
/**
*
*/
private void inicializar()
{
texto = new Texto("Tecla pulsada :");
this.addObject(texto, 80, 332);
}
public void act()
{
}
}
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
/**
*
*/
public class Texto extends Actor
{
private String texto;
public Texto(String texto)
{
this.texto = texto;
this.setImage(new GreenfootImage(texto, 20, Color.WHITE, Color.BLACK));
}
/**
* Act - hace lo que Texto quiere hacer. Este m�todo se llama "cuando quiera" o whenever
* los botones 'Actuar or 'Ejecutar' son presionados en el entorno.
*/
public void act()
{
String tecla = Greenfoot.getKey();
if ( ! tecla.equals(null)) // bad code, if no key is pressed tecla is null and fails
this.actualizar(Greenfoot.getKey());
}
/**
*
*/
public void actualizar(String tecla)
{
this.getImage().clear();
this.getImage().drawString(texto + " " + tecla, this.getX(), this.getY());
}
}

