BreakIterator lineIterator = BreakIterator.getLineInstance(currentLocale);Este BreakIterator determina la posición en que se puede romper una línea para continuar en la siguiente línea. Las posiciones detectadas por el BreakIterator son rupturas de líneas potenciales. La ruptura de línea real mostrada en la pantalla podría no ser la misma.
En los siguientes ejemplos, utilizamos el método markBoundaries para ver los límites de línea detectados por un BreakIterator. Este método imprime marcas en los límites de línea de la cadena fuente.
De acuerdo al BreakIterator, un límite de línea ocurre después del final de una secuencia de caracteres blancos, (space, tab, newline). En el siguiente ejemplo, podemos romper la línea en cualquiera de los límites detectados:
She stopped. She said, "Hello there," and then went on.
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
Las rupturas de líneas potenciales también ocurren inmediatamente después de un guión:
There are twenty-four hours in a day.
^ ^ ^ ^ ^ ^ ^ ^ ^
En el siguiente ejemplo, rompemos una cadena en líneas de la misma longitud con un método llamado formatLines. Utilizamos un BreakIterator para localizar las rupturas de líneas potenciales. Para romper una línea, ejecutamos un System.out.println() siempre que la longitud de la línea actual alcance el valor del parámetro maxLength. El método formatLines es corto, sencillo, y gracias al BreakIterator, independiente de la Localidad. Aquí puedes ver su código fuente:
static void formatLines(String target, int maxLength,
Locale currentLocale) {
BreakIterator boundary = BreakIterator.getLineInstance(currentLocale);
boundary.setText(target);
int start = boundary.first();
int end = boundary.next();
int lineLength = 0;
while (end != BreakIterator.DONE) {
String word = target.substring(start,end);
lineLength = lineLength + word.length();
if (lineLength >= maxLength) {
System.out.println();
lineLength = word.length();
}
System.out.print(word);
start = end;
end = boundary.next();
}
}
En el programa BreakIteratorDemo.java llamamos a
formatLines de esta forma:
String moreText = "She said, \"Hello there,\" and then " +
"went on down the street. When she stopped " +
"to look at the fur coats in a shop window, " +
"her dog growled. \"Sorry Jake,\" she said. " +
" \"I didn't know you would take it personally.\"";
formatLines(moreText, 30, currentLocale);
Aquí podemos ver la salida de la llamada a formatLines:
She said, "Hello there," and
then went on down the
street. When she stopped to
look at the fur coats in a
shop window, her dog
growled. "Sorry Jake," she
said. "I didn't know you
would take it personally."