With
Panneau pan = new Panneau();
you are creating the instance of Panneau
which is modified in the keyPressed
method. But with
this.setContentPane(new Panneau());
you are adding a new instance of Panneau
to the frame - this instance is not modified in the keyPressed
method.
There are some other issues with the code, but the minimal change that is necessary to achieve the desired effect is to change this line to
this.setContentPane(this.pan);
In order to clear the background of the panel (that is, remove the previously painted rectangle) you also have to call super.paintComponent(g)
in the first line of your paintComponent
method:
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(posX, posY, 30, 30);
System.out.print("Carré ");
}