The JTextArea Class

The JTextArea class displays multiple lines of text in a single font and style. Its default behavior is not to wrap lines of text, but line-wrapping can be enabled on word or character boundaries.
Like all Swing JTextComponents (but unlike java.awt.TextArea), JTextArea lacks integrated scrollbars. Fortunately, it is easy to embed a JTextArea inside a JScrollPane for seamless scrolling. (JTextArea implements the Scrollable interface, so JScrollPane can be intelligent about scrolling it.)
JTextArea handles newlines in a cross-platform way. Line separators in text files can be newline (\n), carriage return (\r), or carriage return newline (\r\n), depending on the platform. Swing’s text components remember which line separator was originally used, but always use a newline character to represent one in memory. So always use \n when working with the content of a text component. When writing the content back to disk (or to whatever destination you give the write( ) method), the text component translates newlines back to the remembered type. If there is no remembered type (because the content was created from scratch), newlines are translated to the value of the line.separator system property.

import javax.swing.*;
import javax.swing.text.*;

public class OffsetTest {
	public static void main(String[] args) {
		JTextArea ta = new JTextArea();
		JScrollPane scroll = new JScrollPane(ta);

		// Add three lines of text to the JTextArea.
		ta.append("The first line.\n");
		ta.append("Line Two!\n");
		ta.append("This is the 3rd line of this document.");

		// Print some results.
		try {
			for (int n = 0; n < ta.getLineCount(); n += 1)
				System.out.println("line " + n + " starts at " + 
                               ta.getLineStartOffset(n) + ", ends at "
						+ ta.getLineEndOffset(n));

			int n = 0;
			while (true) {
				System.out.print("offset " + n + " is on ");
				System.out.println("line " + ta.getLineOfOffset(n));
				n += 13;
		} catch (BadLocationException ex) {

		// Layout
		JFrame f = new JFrame();
		f.getContentPane().add(scroll, java.awt.BorderLayout.CENTER);
		f.setSize(150, 150);

You may also like...