1
2
3
4
5
6
7
8
9 package edu.uci.ics.jung.visualization.util;
10
11 import com.google.common.base.Function;
12
13
14
15
16
17
18
19
20 public class LabelWrapper implements Function<String,String> {
21
22 int lineLength;
23 public static final String breaker = "<p>";
24
25
26
27
28
29 public LabelWrapper() {
30 this(10);
31 }
32
33
34
35
36
37 public LabelWrapper(int lineLength) {
38 this.lineLength = lineLength;
39 }
40
41
42
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
54
55
56
57
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 }