1 package org.antlr.xjlib.appkit.utils; 2 3 import org.antlr.xjlib.appkit.gview.base.Vector2D; 4 5 import javax.swing.*; 6 import java.awt.*; 7 import java.awt.event.ActionEvent ; 8 import java.awt.event.ActionListener ; 9 39 40 public class XJSmoothScrolling implements ActionListener { 41 42 protected static final int steps = 10; 43 44 protected JComponent c; 45 protected Rectangle source; 46 protected Rectangle dest; 47 protected Vector2D v; 48 protected int k; 49 protected Timer timer; 50 protected ScrollingDelegate delegate; 51 52 public XJSmoothScrolling(JComponent c, ScrollingDelegate delegate) { 53 this.c = c; 54 this.delegate = delegate; 55 } 56 57 public synchronized void scrollTo(Rectangle dest) { 58 this.dest = dest; 59 computeSource(); 60 computeVector(); 61 if(c.getVisibleRect().intersects(dest)) { 62 c.scrollRectToVisible(dest); 63 completed(); 64 } else { 65 startTimer(); 66 } 67 } 68 69 public synchronized void startTimer() { 70 if(timer != null) 71 timer.stop(); 72 73 timer = new Timer(30, this); 74 timer.start(); 75 k = 0; 76 } 77 78 public void completed() { 79 if(delegate != null) 80 delegate.smoothScrollingDidComplete(); 81 } 82 83 public void computeVector() { 84 v = new Vector2D(dest.x-source.x, dest.y-source.y); 85 } 86 87 public void computeSource() { 88 Rectangle vr = c.getVisibleRect(); 89 source = new Rectangle(dest); 90 if(source.x < vr.x) 91 source.x = vr.x; 92 else if(source.x > vr.x+vr.width) 93 source.x = vr.x+vr.width-source.width; 94 95 if(source.y < vr.y) 96 source.y = vr.y; 97 else if(source.y > vr.y+vr.height) 98 source.y = vr.y+vr.height-source.height; 99 } 100 101 public void actionPerformed(ActionEvent e) { 102 k++; 103 if(k>steps) { 104 c.scrollRectToVisible(dest); 105 timer.stop(); 106 timer = null; 107 completed(); 108 } else { 109 Rectangle current = new Rectangle(source); 110 current.x += v.x*k/steps; 111 current.y += v.y*k/steps; 112 c.scrollRectToVisible(current); 113 } 114 } 115 116 public interface ScrollingDelegate { 117 public void smoothScrollingDidComplete(); 118 } 119 } 120 | Popular Tags |