2012-11-25 43 views
5

Tôi có một JScrollPane với mức tăng khối vừa phải cao (125). Tôi muốn áp dụng chuyển động trơn tru/chậm để nó không nhảy (hoặc bỏ qua) khi cuộn. Tôi có thể làm cái này như thế nào?JScrollPane - Cuộn trơn tru

Tôi đã nghĩ đến việc cuộn như Windows 8.

Mọi trợ giúp sẽ được đánh giá cao!

Trả lời

1

Bạn có thể sử dụng javax.swing.Timer trong khi di chuyển để đạt được hiệu ứng cuộn trơn tru. Nếu bạn đang kích hoạt này từ bên ngoài các thành phần, somthing như thế này sẽ làm việc (nơi component là thành phần trong 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(); 

Phương pháp getFactor là một sự chuyển đổi từ tuyến tính đến một chức năng nới lỏng định và sẽ được thực hiện như một trong những tùy thuộc vào cách bạn muốn nó cảm thấy:

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; 
} 

này có thể có thể được điều chỉnh để làm việc trong một thành phần quá nên khi người dùng cuộn nó làm điều gì đó cùng những dòng này.

Hoặc, nếu có thể, bạn có thể sử dụng JavaFX có hỗ trợ tốt hơn cho hoạt ảnh nhiều hơn Swing.