JTextArea: getLineCount() : JTextArea « javax.swing « Java by API






JTextArea: getLineCount()

 
/*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("java2s\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);
  }
}
           
         
  








Related examples in the same category

1.new JTextArea(Document document)
2.new JTextArea(String text)
3.new JTextArea(String text, int rows, int columns)
4.JTextArea: addCaretListener(CaretListener listener)
5.JTextArea: addUndoableEditListener(UndoableEditListener lis)
6.JTextArea: append(String str)
7.JTextArea: getActionMap()
8.JTextArea: getActions()
9.JTextArea: getCaretPosition()
10.JTextArea: getDocument()
11.JTextArea: getFont()
12.JTextArea: getHighlighter()
13.JTextArea: getKeymap()
14.JTextArea: getLineEndOffset(int line)
15.JTextArea.getLineOfOffset(int offset)
16.JTextArea: getLineStartOffset(int line)
17.JTextArea: insert(String str, int pos)
18.JTextArea: isManagingFocus()
19.JTextArea: paste()
20.JTextArea: read(Reader in, Object desc)
21.JTextArea: replaceRange(String str, int start, int end)
22.JTextArea: setCaretColor(Color c)
23.JTextField: setHorizontalAlignment(int pos)
24.JTextArea: setLineWrap(boolean wrap)
25.JTextArea: setTabSize(int size)
26.JTextArea: setWrapStyleWord(boolean word)
27.JTextArea: write(Writer out)