Question KeyListener how can I send events to another clace [closed]

-1
package prueba;  
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;

public class Ventana extends JFrame implements KeyListener{

    int codigo;

    public int getCodigo() {
        return codigo;
    }

    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }

    public Ventana(){
        addKeyListener(this);
        System.out.println("Tecla Johnn"+codigo);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        codigo=e.getKeyCode();
        if(codigo == KeyEvent.VK_LEFT) {
            System.out.println(codigo);
            //animar(x,y,getCodigo());
            setCodigo(codigo);
        }
        else if(codigo == KeyEvent.VK_RIGHT) {
            System.out.println("Right");
            System.out.println(codigo);
            setCodigo(codigo);
        }
        else if(codigo == KeyEvent.VK_UP) {
            System.out.println("Up");
            System.out.println(codigo);
            setCodigo(codigo);
        }
        else if(codigo == KeyEvent.VK_DOWN) {
            System.out.println("Down");
            System.out.println(codigo);
            setCodigo(codigo);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        //int codigo=e.getKeyCode();
        //System.out.println("Hola"+codigo);
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }   
}
    
asked by Johnn Hidalgo 22.04.2018 в 04:38
source

1 answer

0

Assuming that you have a class called ManejadorEventos and that you want to manipulate in this the events that are generated in class Ventana . First you must have in the class ManejadorEventos methods that receive as parameters objects of the type of event that will handle.

public class ManejadorEventos {
    public void manejarEventoTeclado(KeyEvent event) {
        // aquí irá el código necesario
    }
}

Then you must have an instance of this class in class Ventana and invoke the methods you want by passing them the event objects.

public class Ventana extends JFrame implements KeyListener {

    ManejadorEventos manejador = new ManejadorEventos();

    // Otros atributos

    @Override
    public void keyPressed(KeyEvent e) {
        manejador.manejarEventoTeclado(e);
    }

    // Otros métodos
}

Note that I have created the instance of the event handler class in the same declaration of the attribute, but you could pass the correct instance using the constructor of class Ventana .

    
answered by 22.04.2018 / 05:19
source