4 public class MultiLineLabel extends Canvas {
5 public static final int LEFT = 0;
6 public static final int CENTER = 1;
7 public static final int RIGHT = 2;
8 protected String[] lines;
9 protected int num_lines;
10 protected int margin_width;
11 protected int margin_height;
12 protected int line_height;
13 protected int line_ascent;
14 protected int[] line_widths;
15 protected int max_width;
16 protected int alignment = LEFT;
18 protected void newLabel(String label) {
19 StringTokenizer t = new StringTokenizer(label,"\n");
20 num_lines = t.countTokens();
21 lines = new String[num_lines];
22 line_widths = new int[num_lines];
23 for(int i = 0; i < num_lines; i++) lines[i] = t.nextToken();
26 protected void measure() {
27 FontMetrics fm = this.getFontMetrics(this.getFont());
28 if (fm == null) return;
30 line_height = fm.getHeight();
31 line_ascent = fm.getAscent();
33 for(int i = 0; i < num_lines; i++) {
34 line_widths[i] = fm.stringWidth(lines[i]);
35 if (line_widths[i] > max_width) max_width = line_widths[i];
39 public MultiLineLabel(String label, int margin_width,
40 int margin_height, int alignment) {
42 this.margin_width = margin_width;
43 this.margin_height = margin_height;
44 this.alignment = alignment;
47 public MultiLineLabel(String label, int margin_width, int margin_height) {
48 this(label, margin_width, margin_height, LEFT);
51 public MultiLineLabel(String label, int aligment) {
52 this(label, 10, 10, aligment);
55 public MultiLineLabel(String label) {
56 this(label, 10, 10, LEFT);
59 public void setLabel(String label) {
65 public void setFont(Font f) {
71 public void setForegroundColor(Color c) {
72 super.setForeground(c);
76 public void setAligment(int a) { alignment = a; repaint(); }
77 public void setMarginWidth(int mw) { margin_width = mw; repaint(); }
78 public void setMarginHeight(int mh) { margin_height = mh; repaint(); }
79 public int getAlignment() { return alignment; }
80 public int getMarginWidth() { return margin_width; }
81 public int getMarginheight() { return margin_height; }
83 public void addNotify() { super.addNotify(); measure(); }
85 public Dimension preferedSize() {
86 return new Dimension(max_width + 2 * margin_width,
87 num_lines * line_height + 2 * margin_height);
90 public Dimension miniumSize() {
91 return new Dimension(max_width, num_lines * line_height);
94 public void paint(Graphics g) {
96 Dimension d = this.size();
97 y = line_ascent + (d.height - num_lines * line_height) / 2;
98 for(int i = 0; i < num_lines; i++, y += line_height) {
101 x = margin_width; break;
104 x = (d.width - line_widths[i]) / 2; break;
106 x = d.width - margin_width - line_widths[i]; break;
108 g.drawString(lines[i], x, y);