swing - Animating two images in java -


i'm quite new java. need animate 2 images on java game. it's meant spaceship game allowing 2 users control objects, using keyboard. i've partially implemented this, cannot understand how allow 2 keyboard controls, , 1 object moving via keyboard input flickering lot.

public class mainframe extends jframe implements keylistener {      mainpanel mpanel;         mainpanel secondss;          mainpanel thirdss;         int speed = 5;         //ss facing north         int direction = 0;      mainframe() {         settitle("spaceship game");         mpanel = new mainpanel("c:/img");                 secondss = new mainpanel("c:/img");          setsize(1024, 768);         setdefaultcloseoperation(jframe.exit_on_close);         add(mpanel); // add mainpanel jpanel jframe         setvisible(true); // show class                  add(secondss);                 add(thirdss);                 seconds.currentss.setx(400);                 secondss.currentss.sety(100);     }     public void actionperformed( actionevent e )    {      if( e.getsource() == mpanel)      {      }    }          @override         public void keypressed(keyevent e) {         if (e.getkeycode() == e.vk_left) {           int x = mpanel.currentss.getx() - speed;          mpanel.currentss.setx(x);         }          if (e.getkeycode() == e.vk_right) {          int x = mpanel.currentss.getx() + speed;          mpanel.currentss.setx(x);         }         if (e.getkeycode() == e.vk_down) {          int y = mpanel.currentss.gety() + speed;          mpanel.currentss.sety(y);         }         if (e.getkeycode() == e.vk_up) {          int y = mpanel.currentss.gety() - speed;          mpanel.currentss.sety(y);         }         //change image direction             mpanel.frame = direction;         }      public static void main(string[] args) {         mainframe mainframe = new mainframe();                 mainframe.addkeylistener(mainframe);     } 

if provide or if not point me in right direction grateful.

  • jframe isn't focusable keyevents, default never react keyevents

  • setvisible(true); should last code line, after jcomponents added jframe,

  • for why reason there public void actionperformed( actionevent e ), must generating excpetion form compilier


  • create jframe local variable

  • put jpanel jframe

  • override getpreferredsize jpanel, instesad of setsize jframe

  • then call pack() , setvisble(true)


  • put images java package

  • put images jlabel

  • set nulllayout jpanel (otherwise animations isn't possible)

  • add keybindings jpanel, override desired/required keyevents


  • there way using custom painting, override paintcomponent jpanel, keyevents stays here keybindings better listener in compare keylistener

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -