简体   繁体   中英

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

Well, I'm very(meaning just started a few months ago) new to Programming, I'm learning java.

Anyway, How do I make a sprite move using a timer say:

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

and a Sprite like this:

    private JLabel player = new JLabel(new ImageIcon("Sprites/apple.png"));

With a constructor like this:

 public timing()
{
    Container c = getContentPane();
    c.setLayout(null);
    setVisible(true);
    setSize(1280,720);
    player.setBounds(x,y,100,100); //Use this for moving!
    c.add(player);

    timer.start();
    addKeyListener(
        new KeyAdapter(){

        public void keyPressed(KeyEvent e){
                String key = e.getKeyText(e.getKeyCode());
                if(key.equals("Down"))
                {
                  What Do I put Here?
                }}});


}

So every second, the sprite

  player

will move like

  x+=5 and y+=5

While I am using

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

(I'm very sorry for I'm just a kid learning JAVA)

I assume what you want to do is when you press "down" you want to start a timer.

What you can do is:

if(key.equals("Down"))
{
   long start=System.currentTimeMillis();
   while(start%5000==0)
       repaint();
}

What repaint() does is call the paint() method.

So: What you should do is draw your image in the paint() method. When you call repaint(), you call paint(), so all you need to do is increment x and y by 5 in the paint() method!

Result: Everytime you repaint(), you erase everything in that component and then paint again, but with this x+5 y+5 coordinates, giving the effect of the image moving.

Hope this helps and Good luck!

In your paint() method, create an Ellipse2D object and use the fill method to render "player".

To simplify, assume "player" is a circle

class DrawSurface extends JComponent{
public void paint(Graphics g){

    Graphics2D g = (Graphics2D) g;
    x_pos += 5;
    Shape player = new Ellipse2D.Float(x_pos, 0, 30, 30);
    g.setColor(Color.RED);
    g.fill(player);

}
}

In your keyPress method, add the following

public void keyPressed(KeyEvent e){
            String key = e.getKeyText(e.getKeyCode());
            if(key.equals("Down")){
            DrawSurface canvas = new DrawSurface();
            ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3);
            executor.scheduleAtFixedRate(canvas.paint(), 0L, 30L, TimeUnit.MILLISECONDS);
            }
}

scheduleAtFixedRate executes paint() repeatedly in every 30 time units

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM