拖动旋钮后更改滑块的值

时间:2012-04-10 20:16:31

标签: java swing jslider

我正在尝试使用JSlider setValue(int)在用户完成拖动时自动将旋钮的位置移动到最近的刻度线。当用户点击时,位置设置正确,但是当他们拖动旋钮时则不能。我该如何修复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);
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

相当简单的解决方案,谢谢Andrew Thompson

slider.setSnapToTicks(true);