java - Key Listener not working while using Image and Image Icon -


so, using imageicon , image animate character. far code makes character running reason can't figure out keylistener not working. have been @ while , wondering doing wrong. code: *right took out moving , down because couldn't side side work. velyy going change in y.

    import java.awt.borderlayout;     import java.awt.graphics;     import java.awt.mediatracker;     import java.awt.event.actionevent;     import java.awt.event.actionlistener;     import java.awt.event.*;     import java.awt.event.keyevent;     import javax.swing.imageicon;     import javax.swing.jframe;     import javax.swing.jpanel;     import javax.swing.timer;     import java.awt.image;     public class main extends jpanel implements actionlistener,keylistener{     imageicon images[];     int x = 100;     int y = 5;     int velx;     int vely;     int totalimages =3, currentimage = 0, animationdelay = 160;     timer animationtimer;     public main() {     images = new imageicon[totalimages];     images[0] = new imageicon("standing.png");     images[1] = new imageicon("ready.png");     images[2] = new imageicon("running.png");     startanimation();     }      public void paintcomponent(graphics g) {     super.paintcomponent(g);     graphics g2 = (graphics) g;     if (images[currentimage].getimageloadstatus() == mediatracker.complete){     image img =  images[currentimage].getimage();     g2.drawimage(img, x, 407, null);     currentimage = (currentimage + 1) % totalimages;      }     }      public void actionperformed(actionevent e) {     repaint();     x+=velx;     }      public void right(){     velx = 8;     }     public void left(){     velx = -8;         }      public void keypressed(keyevent arg0) {     int code = arg0.getkeycode();     if (code == keyevent.vk_a){     left();      }     if(code == keyevent.vk_d){     right();      }     }     public void keytyped(keyevent e){}     public void keyreleased(keyevent e){     velx = 0;     vely = 0;     }     public void startanimation() {      if (animationtimer == null) {       currentimage = 0;      animationtimer = new timer(animationdelay, this);      animationtimer.start();      } else if (!animationtimer.isrunning())      animationtimer.restart();      }      public void stopanimation() {      animationtimer.stop();       }         }//end class 

you have register keylistener panel, if want manage key events.

the second thing jpanel not focusable default, have make focusable receive key events.

in main constructor, add :

setfocusable(true); // make panel focusable addkeylistener(this); // register key listener 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -