/*line 0 starts at 0, ends at 5
line 1 starts at 5, ends at 12
line 2 starts at 12, ends at 16
offset 0 is on line 0
offset 1 is on line 0
offset 2 is on line 0
offset 3 is on line 0
offset 4 is on line 0
offset 5 is on line 1
offset 6 is on line 1
offset 7 is on line 1
offset 8 is on line 1
offset 9 is on line 1
offset 10 is on line 1
offset 11 is on line 1
offset 12 is on line 2
offset 13 is on line 2
offset 14 is on line 2
offset 15 is on line 2
offset 16 is on line 2
offset 17 is on javax.swing.text.BadLocationException: Can't translate offset to line
*/
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
public class MainClass {
public static void main(String[] args) {
JTextArea ta = new JTextArea();
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(ta);
ta.append("www.\n");
ta.append("rntsoft\n");
ta.append(".com");
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));
System.out.println();
int n = 0;
while (true) {
System.out.print("offset " + n + " is on ");
System.out.println("line " + ta.getLineOfOffset(n));
n += 1;
}
} catch (BadLocationException ex) {
System.out.println(ex);
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(scroll, java.awt.BorderLayout.CENTER);
f.setSize(150, 150);
f.setVisible(true);
}
}