Search code examples
javaswingjslider

Implementing seeking a media file using JSlider in a Swing-based application


I'm creating a simple media player using jlGUI and jAudiotagger libraries.

I've used a JSlider to implement an automatically moving indicator, as the playback progresses.

Now, I have to implement seeking the file by dragging, by registering that slider to generate events.

So the problem is, when register the seeker, the automatic seeking of the slider(while playing) also causes a ChangeEvent, so its seeking to its own position again and again.

How do I implement it?


Solution

  • How about creating a ChangeListener which lets you turn it on and off with a method call?

    So when you're in animation mode it ignores the stateChanged() events.

    When the user clicks on the JSlider (recognize that with a MouseListener), stop the animation and call MyChangeListener.setAnimationMode(false) so that your listener will react to user interaction.

    public class MyChangeListener implements ChangeListener
    {
      boolean animationMode = true;
    
      public void setAnimationMode( boolean mode )
      {
        this.mode = true;
      }
    
      @Override
      public void stateChanged(ChangeEvent arg0)
      {
        if ( !animationMode )
        {
          // do stuff
        }
      }
    }