Io voglio fare un programma che consiste nel spostare un quadrato biaco in una finestra tramite i tasti WASD ecco il codice:
codice:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class Game extends Canvas implements KeyListener{
int xMan = 0;
int yMan = 0;
public Game(){
setSize(600, 600);
setBackground(Color.black);
}
public static void main(String[] args){
JFrame window = new JFrame("BaSSII");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(600, 600);
window.setResizable(false);
window.add(new Game());
window.addKeyListener(new Game());
window.setVisible(true);
}
public void paint(Graphics g){
g.setColor(Color.white);
g.fillRect(xMan * 25, yMan* 25, 25, 25);
}
public void keyPressed(KeyEvent e){
int id = e.getKeyCode();
if(id == KeyEvent.VK_W) {
yMan = yMan + 1;
System.out.println("Up button pressed");
} else if(id == KeyEvent.VK_S){
yMan = yMan - 1;
System.out.println("Down button pressed");
} else if(id == KeyEvent.VK_A){
xMan = xMan - 1;
System.out.println("Left button pressed");
} else if(id == KeyEvent.VK_D){
xMan = xMan + 1;
System.out.println("Right button pressed");
}
this.repaint();
}
public void keyReleased(KeyEvent e){
//do nothing
}
public void keyTyped(KeyEvent e){
//do nothing
}
}
Ma quando lo vado ad eseguire ogni volta che spingo uno dei tasti mi dice nella console che l' ho spinto ma il quadrato rimane immobile...
Dove ho sbagliato?