Here you can find the source of getWordDimensionAtCaret(JTextComponent editor)
public static Dimension getWordDimensionAtCaret(JTextComponent editor)
//package com.java2s; //License from project: Apache License import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import java.awt.*; public class Main { public static Dimension getWordDimensionAtCaret(JTextComponent editor) { try {//from w ww.j a v a2 s .c o m int iCaretPos = editor.getCaretPosition(); int iStart = getWordStart(editor, iCaretPos); int iEnd = getWordEnd(editor, iCaretPos); editor.getText(iStart, iEnd - iStart); return new Dimension(iStart, iEnd); } catch (BadLocationException e) { return getWordDimensionBeforeCaret(editor); } } 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; } public static int getWordEnd(JTextComponent editor, int iOffset) throws BadLocationException { String text = editor.getText(); iOffset = maybeAdjustOffsetToNextWord(text, iOffset); int iEnd = iOffset; for (; iEnd < text.length() && Character.isJavaIdentifierPart(text.charAt(iEnd)); iEnd++) ; if (iEnd == iOffset && !Character.isWhitespace(text.charAt(iEnd))) { // the word is a single, non-identifier character iEnd++; } return iEnd; } public static Dimension getWordDimensionBeforeCaret(JTextComponent editor) { try { int iEnd = editor.getCaretPosition(); int iStart = getPreviousWord(editor, iEnd); editor.getText(iStart, iEnd - iStart); return new Dimension(iStart, iEnd); } catch (BadLocationException e) { return null; } } 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; } 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--) ; if (iOffset < 0) { return iStart; } return getWordStart(editor, iOffset); } }