Ram*_*mus 6 java swing scroll jscrollpane
我有一个JScrollPane具有适度高的块增量(125).我想对其应用平滑/慢速滚动,以便在滚动时不跳转(或跳过).我怎样才能做到这一点?
我在考虑像Windows 8一样滚动.
任何帮助将不胜感激!
javax.swing.Timer
您可以在滚动期间使用 a来实现平滑滚动的效果。如果您从组件外部触发此操作,则类似的操作将会起作用(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();
Run Code Online (Sandbox Code Playgroud)
该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;
}
Run Code Online (Sandbox Code Playgroud)
这也可能适合在组件内工作,因此当用户滚动时,它会沿着这些线路执行某些操作。
或者,如果可能的话,您可以使用 JavaFX,它对动画的支持比 Swing 好得多。