01: /*
02: *******************************************************************************
03: * Copyright (C) 1997-2004, International Business Machines Corporation and *
04: * others. All Rights Reserved. *
05: *******************************************************************************
06: */
07: package com.ibm.icu.dev.demo.impl;
08:
09: import java.text.BreakIterator;
10: import java.awt.*;
11:
12: public class DemoTextBox {
13:
14: public DemoTextBox(Graphics g, String text, int width) {
15: this .text = text;
16: this .chars = new char[text.length()];
17: text.getChars(0, text.length(), chars, 0);
18:
19: this .width = width;
20: this .port = g;
21: this .metrics = g.getFontMetrics();
22:
23: breakText();
24: }
25:
26: public int getHeight() {
27: return (nbreaks + 1) * metrics.getHeight();
28: }
29:
30: public void draw(Graphics g, int x, int y) {
31: int index = 0;
32:
33: y += metrics.getAscent();
34:
35: for (int i = 0; i < nbreaks; i++) {
36: g.drawChars(chars, index, breakPos[i] - index, x, y);
37: index = breakPos[i];
38: y += metrics.getHeight();
39: }
40:
41: g.drawChars(chars, index, chars.length - index, x, y);
42: }
43:
44: private void breakText() {
45: if (metrics.charsWidth(chars, 0, chars.length) > width) {
46: BreakIterator iter = BreakIterator.getWordInstance();
47: iter.setText(text);
48:
49: int start = iter.first();
50: int end = start;
51: int pos;
52:
53: while ((pos = iter.next()) != BreakIterator.DONE) {
54: int w = metrics.charsWidth(chars, start, pos - start);
55: if (w > width) {
56: // We've gone past the maximum width, so break the line
57: if (end > start) {
58: // There was at least one break position before this point
59: breakPos[nbreaks++] = end;
60: start = end;
61: end = pos;
62: } else {
63: // There weren't any break positions before this one, so
64: // let this word overflow the margin (yuck)
65: breakPos[nbreaks++] = pos;
66: start = end = pos;
67: }
68: } else {
69: // the current position still fits on the line; it's the best
70: // tentative break position we have so far.
71: end = pos;
72: }
73:
74: }
75: }
76: }
77:
78: private String text;
79: private char[] chars;
80: private Graphics port;
81: private FontMetrics metrics;
82: private int width;
83:
84: private int[] breakPos = new int[10]; // TODO: get real
85: private int nbreaks = 0;
86: }
|