0

I'm trying to use the JSlider setValue(int) to automatically move the position of the knob to the closest tick when a user finishes dragging it. The position is set correctly when the user clicks, but not when they drag the knob. How do I fix thix?

    /**
     * Called when the slider is moved.
     * 
     * @access  public
     * @param   ChangeEvent
     * @return  void
     */
    public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider) e.getSource();

        if ( ! source.getValueIsAdjusting() ) {
            //let's only allow users to increment by TIMER_SPACING
            int fps = (int) source.getValue();
            int temp = fps % TIMER_SPACING;
            if ( temp > TIMER_SPACING / 2 ) {
                fps += TIMER_SPACING - temp;
            } else {
                fps -= temp;
            }

            source.setValue(fps);

            if ( fps == 0 ) {
                timer.stop();
            } else {
                if ( ! timer.isRunning() ) {
                    timer.start();
                }
                timer.setDelay(1000 / fps);
            }
        }
    }
Wex
  • 15,539
  • 10
  • 64
  • 107

1 Answers1

2

Quite the simple solution, thank you Andrew Thompson:

slider.setSnapToTicks(true);
Community
  • 1
  • 1
Wex
  • 15,539
  • 10
  • 64
  • 107