blob: 382c69cbde776a2306b52fb0847df6f2c4447ad1 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
package NET.worlds.console;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.util.Vector;
public class TextCanvas extends Canvas {
private static final long serialVersionUID = 2808978760046610505L;
private Dimension calcSize;
private Font font;
private FontMetrics metrics;
private Vector<String> lines = new Vector<String>();
public TextCanvas(String text, int width) {
this.font = new Font(Console.message("CanvasFont"), 0, 12);
this.metrics = Toolkit.getDefaultToolkit().getFontMetrics(this.font);
char[] chars = text.toCharArray();
int start = 0;
int end = 0;
int prevEnd = 0;
int lineWidth = 0;
end = start;
while (end < chars.length) {
char c = chars[end];
boolean isEOL = c == '\n';
if (!isEOL && end == chars.length - 1) {
isEOL = true;
end++;
}
if (c != ' ' && !isEOL) {
end++;
} else {
lineWidth = this.metrics.charsWidth(chars, start, end - start);
if (width != -1 && lineWidth > width) {
end = prevEnd;
} else if ((width == -1 || lineWidth < width) && !isEOL) {
prevEnd = end++;
continue;
}
this.lines.addElement(new String(chars, start, end - start));
start = end + 1;
while (start < chars.length && chars[start] == ' ') {
start++;
}
end = start;
prevEnd = start;
}
}
this.calcSize = new Dimension(width == -1 ? lineWidth : width, this.metrics.getHeight() * this.lines.size());
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setFont(this.font);
g.setColor(Color.black);
int height = this.metrics.getHeight();
int y = this.metrics.getAscent() + this.metrics.getLeading();
for (int i = 0; i < this.lines.size(); i++) {
String line = this.lines.elementAt(i);
g.drawString(line, 0, y);
y += height;
}
}
@Override
public Dimension preferredSize() {
return this.calcSize;
}
}
|