how to use a swing timer to start/stop animation

后端 未结 3 1329
我在风中等你
我在风中等你 2020-11-28 15:28

Could someone teach me how to use a swing timer with the following purpose:

I need to have a polygon that begins being animated(simple animation such a

相关标签:
3条回答
  • 2020-11-28 15:53

    The applet won't listen to clicks because the main thread (the Event Dispatch Thread, EDT) is within the while-loop and isn't listening to your clicks.

    You need another thread. (try using SwingWorker http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html)

    So, the SwingWorker will do the while-loop in the background, publishing results to make your polygon move.

    And the EDT can then focus on any events (like clicks). You can then just use the click-event to kill the SwingWorker if you want to stop it.

    Good luck

    0 讨论(0)
  • 2020-11-28 15:59
    import javax.swing.Timer;
    

    Add an attribute;

    Timer timer; 
    boolean b;   // for starting and stoping animation
    

    Add the following code to frame's constructor.

    timer = new Timer(100, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            // change polygon data
            // ...
    
            repaint();
        }
    });
    

    Override paint(Graphics g) and draw polygon from the data that was modified by actionPerformed(e).

    Finally, a button that start/stop animation has the following code in its event handler.

    if (b) {
        timer.start();
    } else {
        timer.stop();
    }
    b = !b;
    
    0 讨论(0)
  • 2020-11-28 16:00

    This example controls a javax.swing.Timer using a button, while this related example responds to a mouse click. The latter example reverses direction on each click, but start/stop is a straightforward alteration.

    0 讨论(0)
提交回复
热议问题