Search code examples
javaswingawtjtextarea

Get Text and Positions from a Java jTextArea


I want to get the individual texts and their positions as they are entered in an editable jTextArea.

for example ,the following string: "this is java"

should provide the following:

word position this p1 is p2 java p3

any suggestion on how to achieve this. kind regards.


Solution

  • You can do something like this

    JTextArea textArea = new JTextArea();
    textArea.setText("this is java");
    StringTokenizer stringTokenizer = new StringTokenizer(textArea.getText());
    int position = 1;
    while(stringTokenizer.hasMoreTokens())
    {
        System.out.println("Position" + position + ":" + stringTokenizer.nextToken());
    }
    

    Output is

    Position1:this
    Position1:is
    Position1:java
    

    However you wish to know current CaretPosition then you can do textArea.getCaretPosition();.