Here you can find the source of getWordStart(JTextComponent c, int offs)
Parameter | Description |
---|---|
c | the editor |
offs | the offset in the document >= 0 |
public static final int getWordStart(JTextComponent c, int offs) throws BadLocationException
//package com.java2s; /*//from w ww . j a v a2 s . c o m * @(#)Utilities.java 1.40 03/01/23 * * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ import javax.swing.text.*; import java.text.*; public class Main { /** * Determines the start of a word for the given model location. * Uses BreakIterator.getWordInstance() to actually get the words. * * @param c the editor * @param offs the offset in the document >= 0 * @return the location in the model of the word start >= 0 * @exception BadLocationException if the offset is out of range */ public static final int getWordStart(JTextComponent c, int offs) throws BadLocationException { Document doc = c.getDocument(); Element line = getParagraphElement(c, offs); if (line == null) { throw new BadLocationException("No word at " + offs, offs); } int lineStart = line.getStartOffset(); int lineEnd = Math.min(line.getEndOffset(), doc.getLength()); String s = doc.getText(lineStart, lineEnd - lineStart); if (s != null && s.length() > 0) { BreakIterator words = BreakIterator.getWordInstance(c.getLocale()); words.setText(s); int wordPosition = offs - lineStart; if (wordPosition >= words.last()) { wordPosition = words.last() - 1; } words.following(wordPosition); offs = lineStart + words.previous(); } return offs; } /** * Determines the element to use for a paragraph/line. * * @param c the editor * @param offs the starting offset in the document >= 0 * @return the element */ public static final Element getParagraphElement(JTextComponent c, int offs) { Document doc = c.getDocument(); if (doc instanceof StyledDocument) { return ((StyledDocument) doc).getParagraphElement(offs); } Element map = doc.getDefaultRootElement(); int index = map.getElementIndex(offs); Element paragraph = map.getElement(index); if ((offs >= paragraph.getStartOffset()) && (offs < paragraph.getEndOffset())) { return paragraph; } return null; } }