Debian Codegraph @

demos/src/main/java/com/ibm/icu/dev/demo/impl/DemoTextBox.java

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