6

Tengo una clase ejecutándose en un thread que lo único que hace es llamar a un "controlador" que le dice si se ha pulsado o no una tecla en el teclado.

Básicamente el KeyEvent detecta si se ha pulsado alguna tecla, y si es una de las flechas del teclado, guarda true en up, down, left o right.

Hasta ahí todo bien.

El problema viene cuando se inicia el método getPressedKey cuando entra a ese método los 4 boolean están en false, es decir, el método keyPressed ha actualizado los boolean en su thread, pero no en el thread que ejecuta el método getPressedKey.

He hecho los boolean 'volatile', pero no veo ninguna mejoría.

Edito con ejemplo mínimo:

MainApp.java

public class MainApp {

public static void main(String[] args) {

    Frame f = new Frame();
    f.setVisible(true);

    Game j = new Game();
    Player p = new Player(j);

    p.start();

}

}

Frame.java

import javax.swing.JFrame;

public class Frame extends JFrame{

private static final long serialVersionUID = 1L;

Game panel = new Game();

public Frame() {
    super();
    initialize();
}

private void initialize() {
    this.setTitle("Evitar objeto");
    this.add(panel);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setSize(600,600);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
    this.setResizable(false);
    panel.addKeyListener(panel);
    panel.setFocusable(true);
}
}

Player.java

public class Player extends Thread{

public int x, y;
private boolean playing;
private Game game;

public Player(Game j) {

    x = 300-15;
    y = 300-28;
    playing = true;
    game = j;
}



public void run() {

    try {

        while(playing) {

            sleep(500);

            System.out.println(game.getPressedKey());
        }

    }catch(InterruptedException e) {}

}

}

Game.java

import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.ActionEvent; 

public class Game extends JPanel implements ActionListener, KeyListener {

private static final long serialVersionUID = 1L;

private Timer timer;

private Image player;

public int x, y, x_pelota, y_pelota;
private volatile boolean up;
private volatile boolean down;
private volatile boolean left;
private volatile boolean right;

private Player p;

public Game(){

    resetArrows();

    ImageIcon pertsonaiaIcon = new ImageIcon();
    player = pertsonaiaIcon.getImage();

    timer = new Timer(15, this);
    timer.start();
}

private void resetArrows() {
    up = false;
    down = false;
    left = false;
    right = false;
}

public int getPressedKey() {
    int ret;
    if (up) {
        ret = 0;
    }else if (down) {
        ret = 1;
    }else if (left) {
        ret = 2;
    }else if (right) {
        ret = 3;
    }else {
        ret = -1;
    }

    resetArrows();

    return ret;
}

@Override
public void paint(Graphics g){
    super.paint(g);
    g.drawImage(player, 0, 0, this);
}

@Override
public void actionPerformed(ActionEvent e){ 
    repaint();
}

@Override
public synchronized void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    switch(keyCode) { 
    case KeyEvent.VK_UP:
        resetArrows();
        up = true;
        break;
    case KeyEvent.VK_DOWN:
        resetArrows();
        down = true;
        break;
    case KeyEvent.VK_LEFT:
        resetArrows();
        left = true;
        break;
    case KeyEvent.VK_RIGHT :
        resetArrows();
        right = true;
        break;
    }
}

@Override
public void keyReleased(KeyEvent e) {}

@Override
public void keyTyped(KeyEvent e) {}


}
6
  • ¿Es el mismo objeto en todos los thread o tienes varias instancias? ¿Podrías crear un ejemplo mínimo verificable? el 25 sep. 2018 a las 13:08
  • @PabloLozano El código que estoy mostrando está en un JPanel, que a su vez está en un JFrame. El JFrame lo muestra el thread "principal" por así decirlo. Después en otro thread que creo tengo un objeto (una sola instancia) que llama a getPressedKey() cada 100 milisegundos. El objetivo es saber cada 100 milisegundos si se ha pulsado alguna de las flechas en el Frame.
    – Unknown
    el 25 sep. 2018 a las 13:12
  • probaste declarando las variables como estaticas? el 25 sep. 2018 a las 13:17
  • @PabloLozano He editado con un ejemplo mínimo
    – Unknown
    el 25 sep. 2018 a las 13:28
  • @Unknown Muchas gracias, así es fácil ver el problema :) el 25 sep. 2018 a las 13:44

1 respuesta 1

4

Como me imaginaba, el problema es que tienes dos instancias distintas de la clase Game:

En la clase MainApp hay

Game j = new Game();

Y en la clase Frame tienes

Game panel = new Game();

La solución pasa por (por ejemplo), cambiar main a :

public static void main(String[] args) {

    Frame f = new Frame();
    f.setVisible(true);

    Game j = f.panel; // en lugar de crear un nuevo Game, usamos el ya creado
    Player p = new Player(j);

    p.start();

}
1
  • Mil gracias! Solucionado :)
    – Unknown
    el 25 sep. 2018 a las 19:08

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.