Java JTextComponent Word searchInTxComp(JTextComponent src, String word)

Here you can find the source of searchInTxComp(JTextComponent src, String word)

Description

Returns offset of the given word in src the component

License

Open Source License

Parameter

Parameter Description
src source component
word desired word

Return

position offset

Declaration

public static int searchInTxComp(JTextComponent src, String word) 

Method Source Code

//package com.java2s;
/*//from   w  w  w  .  j  a  v a 2 s.  co m
 * Copyright (c) 2013. Chandra Tungaturthi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class Main {
    /**
     * Returns offset of the given word in src the component
     *
     * @param src source component
     * @param word desired word
     * @return position offset
     */
    public static int searchInTxComp(JTextComponent src, String word) {
        int firstOffset = -1;

        if (word == null || word.isEmpty()) {
            return -1;
        }

        // Look for the word we are given - insensitive searchInTxComp
        String content = null;
        try {
            Document d = src.getDocument();

            content = d.getText(0, d.getLength()).toLowerCase();
        } catch (BadLocationException e) {
            // Cannot happen
            return -1;
        }

        word = word.toLowerCase();
        int lastIndex = 0;
        int wordSize = word.length();

        while ((lastIndex = content.indexOf(word, lastIndex)) != -1) {
            int endIndex = lastIndex + wordSize;

            if (firstOffset == -1) {
                firstOffset = lastIndex;
            }
            lastIndex = endIndex;
        }

        return firstOffset;
    }
}

Related

  1. getWordEnd(JTextComponent c, int offs)
  2. getWordEnd(JTextComponent editor, int iOffset)
  3. getWordStart(JTextComponent c, int offs)
  4. getWordWrappedTextDimension(JTextComponent textComponent, int width)
  5. replaceWordAtCaretNice(JTextComponent editor, String strText)
  6. selectWordAtCaret(JTextComponent editor)