Java Swing How to - Break text in JTextArea by sentence








Question

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

Answer

/* w ww  .  j  a  v  a2  s.  c  o  m*/
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.getSentenceInstance(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));
  }
}