繁体   English   中英

如何使用Java中的计时器使Sprite移动?

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

好吧,我对编程非常陌生(意思是几个月前才开始),我正在学习Java。

无论如何,如何使用计时器移动精灵说:

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

和这样的雪碧:

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

使用这样的构造函数:

 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?
                }}});


}

所以每秒钟,精灵

  player

会像

  x+=5 and y+=5

当我使用时

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

(对不起,我只是一个学习JAVA的孩子)

我假设您想做的就是当您按下“向下”按钮时要启动一个计时器。

您可以做的是:

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

repaint()所做的就是调用paint()方法。

因此:您应该做的是在paint()方法中绘制图像。 当您调用repaint()时,您将调用paint(),因此您所要做的就是在paint()方法中将x和y递增5!

结果:每次repaint()时,都会擦除该组件中的所有内容,然后再次绘制,但是使用此x + 5 y + 5坐标,从而产生了图像移动的效果。

希望这会有所帮助,祝你好运!

在paint()方法中,创建一个Ellipse2D对象,然后使用fill方法呈现“玩家”。

为了简化,假设“玩家”是一个圆圈

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);

}
}

在您的keyPress方法中,添加以下内容

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每30个时间单位重复执行paint()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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