Witam, mam problem w programie, którego zadaniem jest poruszanie elementem za pomocą klawiatury. Zaimplementowałem póki co tylko ruch w lewo (strzałką w lewo na klawiaturze) i chciałem przetestować, czy to działa...niestety nie działa! Już parę razy używałem interfejsu KeyListener i wiem, z grubsza, jak działa. Natomiast nie wiem, dlaczego nie zmienia odpowiednio współrzędnych obiektu, przemieszczając go (w tym wypadku w lewo). Oto kod:
Klasa Main:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Main extends Applet implements KeyListener{
int width=400, height=400;
Element cialo[]= new Element[3];
public void init(){
setSize(width, height);
cialo[0]= new Element();
cialo[1]= new Element(cialo[0].getX()+15, cialo[0].getY());
cialo[2]= new Element(cialo[1].getX()+15, cialo[1].getY());
addKeyListener(this);
}
public void paint(Graphics g){
g.clearRect(0,0, width, height);
for(int i=0; i<cialo.length; i++){
cialo[i].narysuj(g);
//System.out.println("cialo["+i+"].getX()="+ cialo[i].getX());
//System.out.println("cialo["+i+"].getY()="+ cialo[i].getY());
//System.out.println("cialo["+i+"].getXnowe(0)="+ cialo[i].getXnowe(0));
//System.out.println("cialo["+i+"].getYnowe()="+ cialo[i].getYnowe());
}
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyChar()==KeyEvent.VK_LEFT){
for(int j=0; j<cialo.length; j++){
//ustawianie nowych wspolrzednych:
cialo[j].setXnowe(cialo[j].getX()-15);
cialo[j].setYnowe(cialo[j].getY());
}
repaint();
}
}
}
Klasa Element:
import java.awt.Graphics;
import java.util.Random;
public class Element {
private int x;
private int y;
private int xnowe;
private int ynowe;
Random losowe= new Random();
public Element(){
this.x=losowe.nextInt(400);
this.y=losowe.nextInt(400);
}
public Element(int x0, int y0){
this.x=x0;
this.y=y0;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getXnowe() {
return xnowe;
}
public void setXnowe(int xnowe) {
this.xnowe = xnowe;
this.x=xnowe;
}
public int getYnowe() {
return ynowe;
}
public void setYnowe(int ynowe) {
this.ynowe = ynowe;
this.y=ynowe;
}
public void narysuj(Graphics g){
g.drawOval(this.x, this.y, 15, 15);
}
}