Java Swing How to - Break text in JTextArea by word








Question

We would like to know how to break text in JTextArea by word.

Answer

//  w  w  w.j a v a  2s . c om
import java.text.BreakIterator;
import java.util.Locale;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new TextBoundaryFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.show();
  }
}

class TextBoundaryFrame extends JFrame {
  private JTextArea outputText = new JTextArea(6, 40);

  public TextBoundaryFrame() {
    getContentPane().add(new JScrollPane(outputText));

    Locale currentLocale = Locale.getDefault();
    BreakIterator currentBreakIterator = BreakIterator.getWordInstance(currentLocale);

    String text = "The quick, brown fox jump-ed\n"
        + "over the lazy \"dog.\" And then...what happened?";
    currentBreakIterator.setText(text);
    outputText.setText("");

    int from = currentBreakIterator.first();
    int to;
    while ((to = currentBreakIterator.next()) != BreakIterator.DONE) {
      outputText.append(text.substring(from, to) + "|");
      from = to;
    }
    outputText.append(text.substring(from));
  }
}