Google Tag Manager

2009/12/21

aterai

snap to ticks drag JSlider

Code

slider.setUI(new MetalSliderUI() {
  protected TrackListener createTrackListener(final JSlider slider) {
    return new TrackListener() {
      public void mouseDragged(MouseEvent e) {
        if(!slider.getSnapToTicks() || slider.getMajorTickSpacing()==0) {
          super.mouseDragged(e);
          return;
        }
        //case JSlider.HORIZONTAL:
        int halfThumbWidth    = thumbRect.width / 2;
        int trackLength = trackRect.width;
        int trackLeft  = trackRect.x-halfThumbWidth;
        int trackRight = trackRect.x+(trackRect.width-1)+halfThumbWidth;
        int xPos = e.getX();
        int snappedPos = xPos;
        if (xPos < = trackLeft) {
          snappedPos = trackLeft;
        } else if (xPos > = trackRight) {
          snappedPos = trackRight;
        } else {
          //int tickSpacing = slider.getMajorTickSpacing();
          //float actualPixelsForOneTick = trackLength * tickSpacing
          //                                 / (float)slider.getMaximum();
          // a problem if you choose to set a negative MINIMUM for
          // the JSlider; the calculated drag-positions are wrong.
          // Fixed by bobndrew:
          int possibleTickPositions=slider.getMaximum()-slider.getMinimum();
          int tickSpacing = (slider.getMinorTickSpacing()==0)
                            ? slider.getMajorTickSpacing()
                            : slider.getMinorTickSpacing();
          float actualPixelsForOneTick = trackLength * tickSpacing
                                         / (float)possibleTickPositions;
          xPos -= trackLeft;
          snappedPos=(int)(
            (Math.round(xPos/actualPixelsForOneTick)*actualPixelsForOneTick)+0.5)
            +trackLeft;
          offset = 0;
        }
        MouseEvent me = new MouseEvent(
          e.getComponent(), e.getID(), e.getWhen(), e.getModifiers(),
          snappedPos, e.getY(),
          e.getXOnScreen(), e.getYOnScreen(),
          e.getClickCount(), e.isPopupTrigger(), e.getButton());
        super.mouseDragged(me);
      }
    };
  }
});

References