View Javadoc
1   package edu.uci.ics.jung.visualization.renderers;
2   
3   import java.awt.Shape;
4   import java.util.HashMap;
5   import java.util.HashSet;
6   import java.util.Map;
7   import java.util.Set;
8   
9   import javax.swing.Icon;
10  import javax.swing.event.ChangeEvent;
11  import javax.swing.event.ChangeListener;
12  
13  import edu.uci.ics.jung.algorithms.layout.Layout;
14  import edu.uci.ics.jung.visualization.BasicVisualizationServer;
15  import edu.uci.ics.jung.visualization.RenderContext;
16  import edu.uci.ics.jung.visualization.layout.LayoutChangeListener;
17  import edu.uci.ics.jung.visualization.layout.LayoutEvent;
18  import edu.uci.ics.jung.visualization.layout.LayoutEventSupport;
19  import edu.uci.ics.jung.visualization.transform.shape.GraphicsDecorator;
20  
21  public class CachingVertexRenderer<V, E> extends BasicVertexRenderer<V, E> 
22  	implements ChangeListener, LayoutChangeListener<V,E> {
23  	
24  	protected Map<V,Shape> vertexShapeMap = new HashMap<V,Shape>();
25  	
26  	protected Set<V> dirtyVertices = new HashSet<V>();
27  	
28  	@SuppressWarnings({ "rawtypes", "unchecked" })
29  	public CachingVertexRenderer(BasicVisualizationServer<V,E> vv) {
30  		vv.getRenderContext().getMultiLayerTransformer().addChangeListener(this);
31  		Layout<V,E> layout = vv.getGraphLayout();
32  		if(layout instanceof LayoutEventSupport) {
33  			((LayoutEventSupport)layout).addLayoutChangeListener(this);
34  			
35  		}
36  	}
37  	
38      /**
39       * Paint <code>v</code>'s icon on <code>g</code> at <code>(x,y)</code>.
40       */
41      protected void paintIconForVertex(RenderContext<V,E> rc, V v, Layout<V,E> layout) {
42          GraphicsDecorator g = rc.getGraphicsContext();
43          boolean vertexHit = true;
44          int[] coords = new int[2];
45          Shape shape = vertexShapeMap.get(v);
46          if(shape == null || dirtyVertices.contains(v)) {
47          	shape = prepareFinalVertexShape(rc, v, layout, coords);
48          	vertexShapeMap.put(v, shape);
49          	dirtyVertices.remove(v);
50          }
51          vertexHit = vertexHit(rc, shape);
52          if (vertexHit) {
53          	if(rc.getVertexIconTransformer() != null) {
54          		Icon icon = rc.getVertexIconTransformer().apply(v);
55          		if(icon != null) {
56          		
57             			g.draw(icon, rc.getScreenDevice(), shape, coords[0], coords[1]);
58  
59          		} else {
60          			paintShapeForVertex(rc, v, shape);
61          		}
62          	} else {
63          		paintShapeForVertex(rc, v, shape);
64          	}
65          }
66      }
67  
68  	public void stateChanged(ChangeEvent evt) {
69  		System.err.println("got change event "+evt);
70  		vertexShapeMap.clear();
71  		
72  	}
73  
74  	public void layoutChanged(LayoutEvent<V,E> evt) {
75  		this.dirtyVertices.add(evt.getVertex());
76  	}
77  }