Frage

I'm programing a game Bomberman-like, and I have a problem with my KeyListener.

The thing is, when the game is running, the KeyListener doesn't respond, but when it's not running, it does what I tell him to.

Here is my code

public class direction extends Canvas implements KeyListener {

static float bmx = 35;
static float bmy = 35;
static float v = 0.03f;

public static BufferStrategy strategie;
public static BufferedImage image;

public direction()  {                                           //pas sûr de ce que ça fait
    GraphicsEnvironment ge =                                    //on m'a dit de le mettre           
            GraphicsEnvironment.getLocalGraphicsEnvironment();  //le programme marche très bien sans
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    GraphicsConfiguration gc = gd.getDefaultConfiguration();
    image =  gc.createCompatibleImage(700,  700);
    setSize(700, 700);

}

    static boolean gauche;
    static boolean droite;
    static boolean haut;
    static boolean bas;


    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            gauche = true;
        }
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            droite = true;
            System.out.println("lal");
        }
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            bas = true;
        }
        if (e.getKeyCode() == KeyEvent.VK_UP) {
            haut = true;
        }
    }
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            gauche = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            droite = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            bas = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_UP) {
            haut = false;
        }
    }
    public void keyTyped(KeyEvent e) {
    }


public static void draw(){

    Graphics2D g = (Graphics2D) strategie.getDrawGraphics();

    for(int ligne= 0 ; ligne < board.gridHauteur; ligne++){
        for(int colonne= 0 ; colonne < board.gridLargeur ; colonne++){

            switch (board.plateau1[ligne][colonne]) {
            case 0 : g.setColor(Color.lightGray);
            g.fillRect( 30*ligne, 30*colonne , 30, 30);
            break;
            case 1 : g.setColor(Color.black);              //dessine et donne la propriété 'BLOCKED' à certains bloques
            g.fillRect( 30*ligne, 30*colonne , 30, 30);
            board.plateau1[ligne][colonne] = board.BLOCKED;
            break;
            case 2 : g.setColor(Color.darkGray);
            g.fillRect( 30*ligne, 30*colonne , 30, 30);
            board.plateau1[ligne][colonne] = board.BLOCKED;
            break;
            }
        }
    }
    g.setColor(Color.red);
    g.fillRect((int)bmx, (int)bmy, 20, 20);   //dessine le "joueur"
    strategie.show();
}

public static void run() {

    long dernierTempsLoop = System.currentTimeMillis();   // avec cette ligne, nous demandons un t0

    while(true) {

        long delta = (System.currentTimeMillis() - dernierTempsLoop); // puis, à chaque nouvel boucle
        dernierTempsLoop = System.currentTimeMillis();               //nous calculons le temps que la 
                                                                    //boucle à mise pour s'effectuer

        for (int i=0;i<delta / 5;i++) {
            logic(5);                   //permet d'appeler à ce qu'il y ait peu de mouvements si la boucle est rapide
        }                               // et plus de mouvements si elle est plus lente ce qui garantit une vitesse constante
                                        // quelle que soit le temps que la boucle met pour s'effectuer
        if ((delta % 5) != 0) {
            logic(delta % 5);
        }

        draw();     //dessine le terrain et le rectangle

        try { Thread.sleep(10); } catch (Exception e) {};   //permet au programme de ne pas "surchauffer"
    }

} }

then

public board()
{
    super("Bomberman");
    setSize(fenLargeur,fenHauteur);
    g = new direction();
    g.setFocusable(true);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().setBackground(Color.BLACK);

    JPanel content = new JPanel();
    content.setLayout(new BorderLayout());
    content.add(g, BorderLayout.CENTER);
    g.addKeyListener(g);                            // <=== c'est CA qui me pose problème
    setContentPane(content);
    setVisible(true);


    g.createBufferStrategy(2);
    Bm.direction.strategie = g.getBufferStrategy();

}`

and...

dispose();
        board b = new board();
        b.g.createBufferStrategy(2);
        direction.strategie = b.g.getBufferStrategy();

        direction.run();

I hope I'm understandable, and thank you for reading.

War es hilfreich?

Lösung

I think your problem might be that at the end of drawing everything you might need to do:

g.setFocusable(true);
g.requestFocusInWindow();

not only :

g.setFocusable(true);

Andere Tipps

Try implementing KeyListener interface in a seperate class.

public class MyListener implements KeyListener{

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

    }

}

And add this interface to your graphical context.

g.addKeyListener(new MyListener ());

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top