How do I to make a sprite move using a timer in java? -


well, i'm very(meaning started few months ago) new programming, i'm learning java.

anyway, how make sprite move using timer say:

  private timer timer = new timer(5000,this); 

and sprite this:

    private jlabel player = new jlabel(new imageicon("sprites/apple.png")); 

with constructor this:

 public timing() {     container c = getcontentpane();     c.setlayout(null);     setvisible(true);     setsize(1280,720);     player.setbounds(x,y,100,100); //use moving!     c.add(player);      timer.start();     addkeylistener(         new keyadapter(){          public void keypressed(keyevent e){                 string key = e.getkeytext(e.getkeycode());                 if(key.equals("down"))                 {                   put here?                 }}});   } 

so every second, sprite

  player 

will move

  x+=5 , y+=5 

while using

  public void paint(graphics g) {     super.paint(g);     player.setbounds(x,y,100,400); } 

(i'm sorry i'm kid learning java)

i assume want when press "down" want start timer.

what can is:

if(key.equals("down")) {    long start=system.currenttimemillis();    while(start%5000==0)        repaint(); } 

what repaint() call paint() method.

so: should draw image in paint() method. when call repaint(), call paint(), need increment x , y 5 in paint() method!

result: everytime repaint(), erase in component , paint again, x+5 y+5 coordinates, giving effect of image moving.

hope helps , luck!


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -