View Javadoc
1   /*
2    * Copyright (c) 2005, The JUNG Authors
3    * All rights reserved.
4    *
5    * This software is open-source under the BSD license; see either "license.txt"
6    * or https://github.com/jrtom/jung/blob/master/LICENSE for a description.
7    *
8    */
9   package edu.uci.ics.jung.visualization.util;
10  
11  import com.google.common.base.Function;
12  
13  /**
14   * A utility to wrap long lines, creating html strings
15   * with line breaks at a settable max line length
16   * 
17   * @author Tom Nelson - tomnelson@dev.java.net
18   *
19   */
20  public class LabelWrapper implements Function<String,String> {
21  
22  	int lineLength;
23  	public static final String breaker = "<p>";
24  	
25  	/**
26  	 * Create an instance with default line break length = 10
27  	 *
28  	 */
29  	public LabelWrapper() {
30  		this(10);
31  	}
32  	
33  	/**
34  	 * Create an instance with passed line break length
35  	 * @param lineLength the max length for lines
36  	 */
37  	public LabelWrapper(int lineLength) {
38  		this.lineLength = lineLength;
39  	}
40  
41  	/**
42  	 * call 'wrap' to transform the passed String
43  	 */
44  	public String apply(String str) {
45  		if(str != null) {
46  			return wrap(str);
47  		} else {
48  			return null;
49  		}
50  	}
51  	
52  	/**
53  	 * line-wrap the passed String as an html string with
54  	 * break Strings inserted.
55  	 * 
56  	 * @param str
57  	 * @return
58  	 */
59  	private String wrap(String str) {
60  		StringBuilder buf = new StringBuilder(str);
61  		int len = lineLength;
62  		while(len < buf.length()) {
63  			int idx = buf.lastIndexOf(" ", len);
64  			if(idx != -1) {
65  				buf.replace(idx, idx+1, breaker);
66  				len = idx + breaker.length() +lineLength;
67  			} else {
68  				buf.insert(len, breaker);
69  				len += breaker.length() + lineLength;
70  			}
71  		}
72  		buf.insert(0, "<html>");
73  		return buf.toString();
74  	}
75  	
76  	public static void main(String[] args) {
77  		String[] lines = {
78  				"This is a line with many short words that I will break into shorter lines.",
79  				"thisisalinewithnobreakssowhoknowswhereitwillwrap",
80  				"short line"
81  		};
82  		LabelWrapper w = new LabelWrapper(10);
83  		for(int i=0; i<lines.length; i++) {
84  			System.err.println("from "+lines[i]+" to "+w.wrap(lines[i]));
85  		}
86  	}
87  }