0

I'm a beginer in coding with java (and in english too) and I'm trying to make a pong game with eclipse. My Problem is that I don't know how to make moove my 2 Rackets (JLabel) by pressing differents keys on keyboard. I first try with KeyListener but I didn't suceed, so now I try with keyBinding, I read a lot of tutorial but I don't really understood.

So How I can simply make my two rackets moove by pressing the arrows keys.

Here a part of the code :

import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;

public class Pongg extends JPanel implements KeyListener {


private JLabel Racket1;                   // <----- Déclaration des JLabel/JLayeredPane ici pour pouvoir les utiliser (KeyListener)
private JLabel Racket2;                   //


public Pongg() {


    //Création de la fenetre
    JFrame fenetre = new JFrame("Fenetre");
    fenetre.setLocationRelativeTo (null);
    fenetre.setVisible(true);
    fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    fenetre.setSize(1000,600);

    //Box Main + JLayeredPane (fond noir)
    Box main=Box.createVerticalBox();
    JLayeredPane Fond = new JLayeredPane();
    Fond.setBackground(Color.black);        
    Fond.setOpaque(true);
    Fond.setVisible(true);

    main.add(Fond);
    fenetre.add(main);

    //Plateformes
    JLabel Racket1 = new JLabel();
    JLabel Racket2 = new JLabel();      

    //--->Racket 1 :        
    Racket1.setBounds(50, 200, 16, 100);   //<----- setBounds (Placer position du JLabel x,y + taille de la plateforme x,y)
    Racket1.setBackground(Color.white);
    Racket1.setOpaque(true);



    //--->Racket 2 :

    Racket2.setBounds(900, 200, 16, 100);
    Racket2.setBackground(Color.white);
    Racket2.setOpaque(true);

    Fond.add(Racket1); 
    Fond.add(Racket2);

EDDIT : here I tried to do it with keyListener (I have no idea how to do it with keyBinding) :

private Set appuye = new HashSet();

    public void keyTyped(KeyEvent e) {
    }

    public void keyPressed(KeyEvent e) {
        appuye.add(e.getKeyCode()); // On ajoute le nombre correspondant à la touche pressée à la liste
            if (appuye.contains(KeyEvent.VK_UP)) { // la liste contient-elle cette touche ? (c'est un int static, donc utilisable à partir de la classe, même sans objet)
                Racket1.setLocation(Racket1.getX(), Racket1.getY() - 16);
            }
            if (appuye.contains(KeyEvent.VK_DOWN)) {
                Racket1.setLocation(Racket1.getX(), Racket1.getY() + 16);
            }
            if (appuye.contains(KeyEvent.VK_A)) {
                Racket2.setLocation(Racket2.getX(), Racket2.getY() - 16);
            }
            if (appuye.contains(KeyEvent.VK_Q)) {
                Racket2.setLocation(Racket2.getX(), Racket2.getY() + 16);
            }
    }

    public void keyReleased(KeyEvent e) {
        appuye.remove(e.getKeyCode()); // Lorsque la touche est relachée, on retire son numéro de la liste.

}           
Silver
  • 11
  • 4

0 Answers0