gpt4 book ai didi

java - JScrollPane - 平滑滚动

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:33:19 24 4
gpt4 key购买 nike

我有一个 block 增量适中的 JScrollPane (125)。我想对其应用平滑/慢速滚动,这样它在滚动时不会跳跃(或跳过)。我该怎么做?

我想像 Windows 8 那样滚动。

如有任何帮助,我们将不胜感激!

最佳答案

您可以在滚动过程中使用javax.swing.Timer 来实现平滑的滚动效果。如果您是从组件外部触发它,那么类似这样的事情将起作用(其中 componentJScrollPane 中的组件):

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 好得多。

关于java - JScrollPane - 平滑滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13550569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com