JScrollPane - 平滑滚动

6

我有一个带有相当高的块增量(125)的JScrollPane。我想对它应用平滑/缓慢滚动,这样在滚动时就不会跳跃或跳过内容。我该怎么做?

我考虑像Windows 8一样滚动。

非常感谢您的帮助!

1个回答

2

您可以在滚动期间使用javax.swing.Timer来实现平滑的滚动效果。如果您是从组件外部触发此操作,则可以使用以下代码(其中component是位于JScrollPane中的组件):

final int target = visible.y;
final Rectangle current = component.getVisibleRect();
final int start = current.y;
final int delta = target - start;
final int msBetweenIterations = 10;

Timer scrollTimer = new Timer(msBetweenIterations, new ActionListener() {
    int currentIteration = 0;
    final long animationTime = 150; // milliseconds
    final long nsBetweenIterations = msBetweenIterations * 1000000; // nanoseconds
    final long startTime = System.nanoTime() - nsBetweenIterations; // Make the animation move on the first iteration
    final long targetCompletionTime = startTime + animationTime * 1000000;
    final long targetElapsedTime = targetCompletionTime - startTime;

    @Override
    public void actionPerformed(ActionEvent e) {
        long timeSinceStart = System.nanoTime() - startTime;
        double percentComplete = Math.min(1.0, (double) timeSinceStart / targetElapsedTime);

        double factor = getFactor(percentComplete);
        current.y = (int) Math.round(start + delta * factor);
        component.scrollRectToVisible(current);
        if (timeSinceStart >= targetElapsedTime) {
            ((Timer) e.getSource()).stop();
        }
    }
});
scrollTimer.setInitialDelay(0);
scrollTimer.start();

getFactor方法是将线性函数转换为缓动函数的方法,具体实现取决于您希望它的感觉如何,以下是其中之一:

private double snap(double percent) {
    return 1;
}

private double linear(double percent) {
    return percent;
}

private double easeInCubic(double percent) {
    return Math.pow(percent, 3);
}

private double easeOutCubic(double percent) {
    return 1 - easeInCubic(1 - percent);
}

private double easeInOutCubic(double percent) {
    return percent < 0.5
            ? easeInCubic(percent * 2) / 2
            : easeInCubic(percent * -2 + 2) / -2 + 1;
}

这个功能可能可以适应组件内部的工作方式,因此当用户滚动时,它会执行类似于以下内容的操作。

或者,如果可能的话,您可以使用JavaFX,它比Swing更好地支持动画。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接