Java JTextComponent Word getPreviousWord(JTextComponent editor, int iOffset)

Here you can find the source of getPreviousWord(JTextComponent editor, int iOffset)

Description

get Previous Word

License

Apache License

Declaration

private static int getPreviousWord(JTextComponent editor, int iOffset) throws BadLocationException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import javax.swing.text.BadLocationException;

import javax.swing.text.JTextComponent;

public class Main {
    private static int getPreviousWord(JTextComponent editor, int iOffset) throws BadLocationException {
        String text = editor.getText();
        int iStart = getWordStart(editor, iOffset);
        for (iOffset = iStart - 1; iOffset >= 0 && Character.isWhitespace(text.charAt(iOffset)); iOffset--)
            ;//from  ww  w  .  ja  va2  s  .  co  m
        if (iOffset < 0) {
            return iStart;
        }
        return getWordStart(editor, iOffset);
    }

    public static int getWordStart(JTextComponent editor, int iOffset) throws BadLocationException {
        String text = editor.getText();
        iOffset = maybeAdjustOffsetToNextWord(text, iOffset);

        int iStart = iOffset;
        for (; iStart > 0 && Character.isJavaIdentifierPart(text.charAt(iStart)); iStart--)
            ;
        if (iStart != iOffset) {
            iStart++;
        }
        return iStart;
    }

    private static int maybeAdjustOffsetToNextWord(String text, int iOffset) throws BadLocationException {
        if (text.length() < iOffset) {
            throw new BadLocationException("Index out of bounds. Offset: " + iOffset + "  Length: " + text.length(),
                    iOffset);
        }

        if (iOffset > 0 && !text.isEmpty()
                && (text.length() == iOffset || Character.isWhitespace(text.charAt(iOffset)))) {
            if (Character.isWhitespace(text.charAt(iOffset - 1))) {
                while (iOffset < text.length()) {
                    if (!Character.isWhitespace(text.charAt(iOffset))) {
                        return iOffset;
                    }
                    iOffset++;
                }
            }
            iOffset--;
        }
        return iOffset;
    }
}

Related

  1. getNextWord(JTextComponent c, int offs)
  2. getNextWordInParagraph(JTextComponent c, Element line, int offs, boolean first)
  3. getPartialWordBeforePos(JTextComponent editor, int iPos)
  4. getWordAtCaret(JTextComponent editor)
  5. getWordDimensionAtCaret(JTextComponent editor)
  6. getWordDimensionBeforeCaret(JTextComponent editor)
  7. getWordEnd(JTextComponent c, int offs)