如何使用按钮单击事件停止动画

时间:2016-01-05 17:41:21

标签: java

以下任何人都可以帮助我尝试实现点击事件的一段代码当单击按钮时动画将开始并且可以随时停止。它适用于启动动画,只有停止会产生问题

public class AnimateCircleListener implements ActionListener,MouseListener
 {
    public void actionPerformed(ActionEvent e)
    {

        if(e.getSource() == button)
        {
           flag = true;

           if(flag == true)
          {
              // creates thread object and calls the move method
              Move move = new Move();
              thread = new Thread(move);
              thread.start();

          }

        }
     }

           @Override
            public void mouseClicked(MouseEvent arg0) {



            }


            @Override
            public void mouseEntered(MouseEvent arg0) {

            }

            @Override
            public void mouseExited(MouseEvent arg0) {


            }

            @Override
            public void mousePressed(MouseEvent arg0) {

            }

            @Override
            public void mouseReleased(MouseEvent arg0) {


        }

  }

    public class Move implements Runnable  // method for moving ball
    {
     public void run()
     {
        do
        {
            x = x + xvel;

            if(x + diameter > 484)
            xvel= -1;

            if(x <= 0)
            xvel =  + 1;

            drawPanel.repaint();

            try
              {
              Thread.sleep(10);
              }
               catch(Exception ex)
              {
                  System.out.println("Error");
              }

          }while(decide);  // by default decide = true

       }
     }

1 个答案:

答案 0 :(得分:1)

使用Swing Timer作为动画。

然后,您只需在“开始”按钮中调用start()方法,在“停止”按钮中调用stop()方法。