View Javadoc
1   /*
2    * Created on Jul 19, 2005
3    *
4    * Copyright (c) 2005, The JUNG Authors 
5    *
6    * All rights reserved.
7    *
8    * This software is open-source under the BSD license; see either
9    * "license.txt" or
10   * https://github.com/jrtom/jung/blob/master/LICENSE for a description.
11   */
12  package edu.uci.ics.jung.algorithms.layout.util;
13  
14  import java.awt.Dimension;
15  import java.awt.geom.Point2D;
16  import java.util.Date;
17  import java.util.Random;
18  
19  import com.google.common.base.Function;
20  
21  import edu.uci.ics.jung.algorithms.layout.StaticLayout;
22  
23  /**
24   * Provides a random vertex location within the bounds of the Dimension property.
25   * This provides a random location for unmapped vertices
26   * the first time they are accessed.
27   * 
28   * <p><b>Note</b>: the generated values are not cached, so apply() will generate a new random
29   * location for the passed vertex every time it is called.  If you want a consistent value,
30   * wrap this layout's generated values in a {@link StaticLayout} instance.
31   * 
32   * @author Tom Nelson
33   *
34   * @param <V> the vertex type
35   */
36  public class RandomLocationTransformer<V> implements Function<V,Point2D> {
37  	Dimension d;
38  	Random random;
39      
40      /**
41       * Creates an instance with the specified size which uses the current time 
42       * as the random seed.
43       * @param d the size of the layout area
44       */
45      public RandomLocationTransformer(Dimension d) {
46      	this(d, new Date().getTime());
47      }
48      
49      /**
50       * Creates an instance with the specified dimension and random seed.
51       * @param d the size of the layout area
52       * @param seed the seed for the internal random number generator
53       */
54      public RandomLocationTransformer(final Dimension d, long seed) {
55      	this.d = d;
56      	this.random = new Random(seed);
57      }
58      
59      public Point2D apply(V v) {
60          return new Point2D.Double(random.nextDouble() * d.width, random.nextDouble() * d.height);
61      }
62  }