1 | package utils;
|
---|
2 |
|
---|
3 | import java.awt.*;
|
---|
4 | import java.util.*;
|
---|
5 |
|
---|
6 | public class WrappedString {
|
---|
7 | private ArrayList<String> lstStrings;
|
---|
8 | private FontMetrics metrics;
|
---|
9 |
|
---|
10 | public WrappedString(String str, FontMetrics metrics, int width) {
|
---|
11 | lstStrings = new ArrayList<String>();
|
---|
12 | this.metrics = metrics;
|
---|
13 |
|
---|
14 | while(!str.equals("")) {
|
---|
15 | int cur = 1;
|
---|
16 | int lastSpace = -1;
|
---|
17 | while(cur <= str.length() && metrics.stringWidth(str.substring(0, cur)) < width) {
|
---|
18 | if(str.substring(cur-1, cur).equals(" "))
|
---|
19 | lastSpace = cur-1;
|
---|
20 | cur++;
|
---|
21 | }
|
---|
22 | if(lastSpace == -1 || cur > str.length()) {
|
---|
23 | lstStrings.add(str.substring(0, cur-1));
|
---|
24 | str = str.substring(cur-1);
|
---|
25 | }else {
|
---|
26 | lstStrings.add(str.substring(0, lastSpace));
|
---|
27 | str = str.substring(lastSpace+1);
|
---|
28 | }
|
---|
29 |
|
---|
30 | //get rid of leading spaces
|
---|
31 | while(str.length() > 0 && str.substring(0,1).equals(" "))
|
---|
32 | str = str.substring(1);
|
---|
33 | }
|
---|
34 | }
|
---|
35 |
|
---|
36 | public int getLineCount() {
|
---|
37 | return lstStrings.size();
|
---|
38 | }
|
---|
39 |
|
---|
40 | public String getLine(int index) {
|
---|
41 | return lstStrings.get(index);
|
---|
42 | }
|
---|
43 |
|
---|
44 | public FontMetrics getMetrics() {
|
---|
45 | return metrics;
|
---|
46 | }
|
---|
47 |
|
---|
48 | public void draw(Graphics g, int x, int y) {
|
---|
49 | for(int i=0; i<getLineCount(); i++)
|
---|
50 | g.drawString(getLine(i), x, y+i*metrics.getHeight());
|
---|
51 | }
|
---|
52 | }
|
---|