Example usage for javax.swing.text JTextComponent getCaretPosition

List of usage examples for javax.swing.text JTextComponent getCaretPosition

Introduction

In this page you can find the example usage for javax.swing.text JTextComponent getCaretPosition.

Prototype

@Transient
public int getCaretPosition() 

Source Link

Document

Returns the position of the text insertion caret for the text component.

Usage

From source file:net.sf.jabref.gui.autocompleter.AutoCompleteListener.java

/**
 * Start a new completion attempt (instead of treating a continuation of an existing word or an interrupt of the
 * current word)//from w w  w.  j a v  a 2  s.c  o m
 */
private void startCompletion(StringBuffer currentword, KeyEvent e) {
    JTextComponent comp = (JTextComponent) e.getSource();

    List<String> completed = findCompletions(currentword.toString());
    String prefix = completer.getPrefix();
    String cWord = (prefix != null) && (!prefix.isEmpty()) ? currentword.toString().substring(prefix.length())
            : currentword.toString();

    LOGGER.debug("StartCompletion currentword: >" + currentword + "'<' prefix: >" + prefix + "'<' cword: >"
            + cWord + '<');

    int no = 0; // We use the first word in the array of completions.
    if ((completed != null) && (!completed.isEmpty())) {
        lastShownCompletion = 0;
        lastCompletions = completed;
        String sno = completed.get(no);

        // these two lines obey the user's input
        //toSetIn = Character.toString(ch);
        //toSetIn = toSetIn.concat(sno.substring(cWord.length()));
        // BUT we obey the completion
        toSetIn = sno.substring(cWord.length() - 1);

        LOGGER.debug("toSetIn: >" + toSetIn + '<');

        StringBuilder alltext = new StringBuilder(comp.getText());
        int cp = comp.getCaretPosition();
        alltext.insert(cp, toSetIn);
        comp.setText(alltext.toString());
        comp.setCaretPosition(cp);
        comp.select(cp + 1, (cp + 1 + sno.length()) - cWord.length());
        e.consume();
        lastCaretPosition = comp.getCaretPosition();
        char ch = e.getKeyChar();

        LOGGER.debug("Appending >" + ch + '<');

        if (cWord.length() <= 1) {
            lastBeginning = Character.toString(ch);
        } else {
            lastBeginning = cWord.substring(0, cWord.length() - 1).concat(Character.toString(ch));
        }
    }

}

From source file:net.sf.jabref.gui.AutoCompleteListener.java

/**
 * Start a new completion attempt/*from w w w  . ja  v a 2 s .c om*/
 * (instead of treating a continuation of an existing word or an interrupt of the current word)
 */
private void startCompletion(StringBuffer currentword, KeyEvent e) {
    JTextComponent comp = (JTextComponent) e.getSource();

    String[] completed = findCompletions(currentword.toString(), comp);
    String prefix = completer.getPrefix();
    String cWord = (prefix != null) && (!prefix.isEmpty()) ? currentword.toString().substring(prefix.length())
            : currentword.toString();

    LOGGER.debug("StartCompletion currentword: >" + currentword + "'<' prefix: >" + prefix + "'<' cword: >"
            + cWord + '<');

    int no = 0; // We use the first word in the array of completions.
    if ((completed != null) && (completed.length > 0)) {
        lastShownCompletion = 0;
        lastCompletions = completed;
        String sno = completed[no];

        // these two lines obey the user's input
        //toSetIn = Character.toString(ch);
        //toSetIn = toSetIn.concat(sno.substring(cWord.length()));
        // BUT we obey the completion
        toSetIn = sno.substring(cWord.length() - 1);

        LOGGER.debug("toSetIn: >" + toSetIn + '<');

        StringBuilder alltext = new StringBuilder(comp.getText());
        int cp = comp.getCaretPosition();
        alltext.insert(cp, toSetIn);
        comp.setText(alltext.toString());
        comp.setCaretPosition(cp);
        comp.select(cp + 1, (cp + 1 + sno.length()) - cWord.length());
        e.consume();
        lastCaretPosition = comp.getCaretPosition();
        char ch = e.getKeyChar();

        LOGGER.debug("Appending >" + ch + '<');

        if (cWord.length() <= 1) {
            lastBeginning = Character.toString(ch);
        } else {
            lastBeginning = cWord.substring(0, cWord.length() - 1).concat(Character.toString(ch));
        }
    }

}

From source file:net.sf.jabref.gui.AutoCompleteListener.java

/**
 * If user cancels autocompletion by/*  w w  w . j  a v a2 s.c om*/
 *   a) entering another letter than the completed word (and there is no other auto completion)
 *   b) space
 * the casing of the letters has to be kept
 * 
 * Global variable "lastBeginning" keeps track of typed letters.
 * We rely on this variable to reconstruct the text 
 * 
 * @param wordSeperatorTyped indicates whether the user has typed a white space character or a
 */
private void setUnmodifiedTypedLetters(JTextComponent comp, boolean lastBeginningContainsTypedCharacter,
        boolean wordSeperatorTyped) {
    if (lastBeginning == null) {
        LOGGER.debug("No last beginning found");
        // There was no previous input (if the user typed a word, where no autocompletion is available)
        // Thus, there is nothing to replace
        return;
    }
    LOGGER.debug("lastBeginning: >" + lastBeginning + '<');
    if (comp.getSelectedText() == null) {
        // if there is no selection
        // the user has typed the complete word, but possibly with a different casing
        // we need a replacement
        if (wordSeperatorTyped) {
            LOGGER.debug("Replacing complete word");
        } else {
            // if user did not press a white space character (space, ...),
            // then we do not do anything
            return;
        }
    } else {
        LOGGER.debug("Selected text " + comp.getSelectedText() + " will be removed");
        // remove completion suggestion
        comp.replaceSelection("");
    }

    lastCaretPosition = comp.getCaretPosition();

    int endIndex = lastCaretPosition - lastBeginning.length();
    if (lastBeginningContainsTypedCharacter) {
        // the current letter is NOT contained in comp.getText(), but in lastBeginning
        // thus lastBeginning.length() is one too large
        endIndex++;
    }
    String text = comp.getText();
    comp.setText(text.substring(0, endIndex).concat(lastBeginning).concat(text.substring(lastCaretPosition)));
    if (lastBeginningContainsTypedCharacter) {
        // the current letter is NOT contained in comp.getText()
        // Thus, cursor position also did not get updated
        lastCaretPosition++;
    }
    comp.setCaretPosition(lastCaretPosition);
    lastBeginning = null;
}

From source file:net.sf.jabref.gui.autocompleter.AutoCompleteListener.java

private void cycle(JTextComponent comp, int increment) {
    assert (lastCompletions != null);
    assert (!lastCompletions.isEmpty());
    lastShownCompletion += increment;// www . j av  a  2s .  c  o m
    if (lastShownCompletion >= lastCompletions.size()) {
        lastShownCompletion = 0;
    } else if (lastShownCompletion < 0) {
        lastShownCompletion = lastCompletions.size() - 1;
    }
    String sno = lastCompletions.get(lastShownCompletion);
    toSetIn = sno.substring(lastBeginning.length() - 1);

    StringBuilder alltext = new StringBuilder(comp.getText());

    int oldSelectionStart = comp.getSelectionStart();
    int oldSelectionEnd = comp.getSelectionEnd();

    // replace prefix with new prefix
    int startPos = comp.getSelectionStart() - lastBeginning.length();
    alltext.delete(startPos, oldSelectionStart);
    alltext.insert(startPos, sno.subSequence(0, lastBeginning.length()));

    // replace suffix with new suffix
    alltext.delete(oldSelectionStart, oldSelectionEnd);
    //int cp = oldSelectionEnd - deletedChars;
    alltext.insert(oldSelectionStart, toSetIn.substring(1));

    LOGGER.debug(alltext.toString());
    comp.setText(alltext.toString());
    //comp.setCaretPosition(cp+toSetIn.length()-1);
    comp.select(oldSelectionStart, (oldSelectionStart + toSetIn.length()) - 1);
    lastCaretPosition = comp.getCaretPosition();
    LOGGER.debug("ToSetIn: '" + toSetIn + "'");
}

From source file:net.sf.jabref.gui.AutoCompleteListener.java

private void cycle(JTextComponent comp, int increment) {
    assert (lastCompletions != null);
    assert (lastCompletions.length > 0);
    lastShownCompletion += increment;/*from   w w w.  j a v  a2  s  . co m*/
    if (lastShownCompletion >= lastCompletions.length) {
        lastShownCompletion = 0;
    } else if (lastShownCompletion < 0) {
        lastShownCompletion = lastCompletions.length - 1;
    }
    String sno = lastCompletions[lastShownCompletion];
    toSetIn = sno.substring(lastBeginning.length() - 1);

    StringBuilder alltext = new StringBuilder(comp.getText());

    int oldSelectionStart = comp.getSelectionStart();
    int oldSelectionEnd = comp.getSelectionEnd();

    // replace prefix with new prefix
    int startPos = comp.getSelectionStart() - lastBeginning.length();
    alltext.delete(startPos, oldSelectionStart);
    alltext.insert(startPos, sno.subSequence(0, lastBeginning.length()));

    // replace suffix with new suffix
    alltext.delete(oldSelectionStart, oldSelectionEnd);
    //int cp = oldSelectionEnd - deletedChars;
    alltext.insert(oldSelectionStart, toSetIn.substring(1));

    //Util.pr(alltext.toString());
    comp.setText(alltext.toString());
    //comp.setCaretPosition(cp+toSetIn.length()-1);
    comp.select(oldSelectionStart, (oldSelectionStart + toSetIn.length()) - 1);
    lastCaretPosition = comp.getCaretPosition();
    //System.out.println("ToSetIn: '"+toSetIn+"'");
}

From source file:com.hexidec.ekit.EkitCore.java

/**
 * Method to initiate a find/replace operation
 *//*from w  w  w.  j  a  va 2s . com*/
private void doSearch(String searchFindTerm, String searchReplaceTerm, boolean bIsFindReplace,
        boolean bCaseSensitive, boolean bStartAtTop) {
    boolean bReplaceAll = false;
    JTextComponent searchPane = (JTextComponent) jtpMain;
    if (sourceWindowActive || jtpSource.hasFocus()) {
        searchPane = (JTextComponent) jtpSource;
    }
    if (searchFindTerm == null || (bIsFindReplace && searchReplaceTerm == null)) {
        SearchDialog sdSearchInput = new SearchDialog(this.getWindow(),
                Translatrix.getTranslationString("SearchDialogTitle"), true, bIsFindReplace, bCaseSensitive,
                bStartAtTop);
        searchFindTerm = sdSearchInput.getFindTerm();
        searchReplaceTerm = sdSearchInput.getReplaceTerm();
        bCaseSensitive = sdSearchInput.getCaseSensitive();
        bStartAtTop = sdSearchInput.getStartAtTop();
        bReplaceAll = sdSearchInput.getReplaceAll();
    }
    if (searchFindTerm != null && (!bIsFindReplace || searchReplaceTerm != null)) {
        if (bReplaceAll) {
            int results = findText(searchFindTerm, searchReplaceTerm, bCaseSensitive, 0);
            int findOffset = 0;
            if (results > -1) {
                while (results > -1) {
                    findOffset = findOffset + searchReplaceTerm.length();
                    results = findText(searchFindTerm, searchReplaceTerm, bCaseSensitive, findOffset);
                }
            } else {
                new SimpleInfoDialog(this.getWindow(), "", true,
                        Translatrix.getTranslationString("ErrorNoOccurencesFound") + ":\n" + searchFindTerm,
                        SimpleInfoDialog.WARNING);
            }
        } else {
            int results = findText(searchFindTerm, searchReplaceTerm, bCaseSensitive,
                    (bStartAtTop ? 0 : searchPane.getCaretPosition()));
            if (results == -1) {
                new SimpleInfoDialog(this.getWindow(), "", true,
                        Translatrix.getTranslationString("ErrorNoMatchFound") + ":\n" + searchFindTerm,
                        SimpleInfoDialog.WARNING);
            }
        }
        lastSearchFindTerm = new String(searchFindTerm);
        if (searchReplaceTerm != null) {
            lastSearchReplaceTerm = new String(searchReplaceTerm);
        } else {
            lastSearchReplaceTerm = (String) null;
        }
        lastSearchCaseSetting = bCaseSensitive;
        lastSearchTopSetting = bStartAtTop;
    }
}

From source file:net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent.BaseKeyTextHandler.java

/**
 * Ensure, that a sign character is entered at the right position.
 * Valid characters for a sign is the <code>-</code>. If the corresponding {@link ColumnDisplayDefinition#isSigned()} is 
 * <code>false</code>, than a sign is not allowed for this column.
 * Otherwise, a sign character is allowed at the first position of the text if there is not already a sign char present.
 * <B>If the entered sign character is not valid, then the keyEvent will be consumed and a beep will be processed.</B>
 * <p>For example:</p>// ww w.j  a  v  a2 s.co  m
 * Allowed:
 * <li>42</li>
 * <li>-42</li>
 * Not allowed:
 * <li>-.42</li>
 * <li>--42</li>
 * <li>42-42</li>
 * <li>-42-42</li>
 * <li>42-</li>
 * @param keyEvent KeyEvent, which insert a character
 * @param textComponent Text component, where the character was typed.
 * @param colDef Display definition of the affected column. This will be used, for finding out, if the data type can be signed.
 * @param beepHelper Helper for beeping, if a sign char is would be inserted at a wrong position.
 */
protected void checkSignCharacter(KeyEvent keyEvent, JTextComponent textComponent,
        ColumnDisplayDefinition colDef, IToolkitBeepHelper beepHelper) {
    char c = keyEvent.getKeyChar();
    String text = textComponent.getText();

    if (isSignCharacter(c)) {
        boolean ok = true;
        if (colDef.isSigned() == false) {
            ok = false;
        } else if (!text.equals("<null>") && text.length() != 0) {
            int caretPosition = textComponent.getCaretPosition();
            if (caretPosition != 0 || isSignCharacter(text.charAt(0))) {
                ok = false;
            }
        }
        if (ok == false) {
            /*
             *  user entered '+' or '-' at a bad place,
             *  Maybe not at the first position, or there is not a numeric char at the beginning - maybe we have already a sign
             */
            beepHelper.beep(textComponent);
            keyEvent.consume();
        }
    }
}

From source file:netbeanstypescript.TSCodeCompletion.java

@Override
public QueryType getAutoQuery(JTextComponent component, String typedText) {
    if (typedText.length() == 0) {
        return QueryType.NONE;
    }/*from ww  w .ja  v  a  2 s . c o m*/

    int offset = component.getCaretPosition();
    TokenSequence<? extends JsTokenId> ts = LexUtilities.getJsTokenSequence(component.getDocument(), offset);
    if (ts != null) {
        int diff = ts.move(offset);
        TokenId currentTokenId = null;
        if (diff == 0 && ts.movePrevious() || ts.moveNext()) {
            currentTokenId = ts.token().id();
        }

        char lastChar = typedText.charAt(typedText.length() - 1);
        if (currentTokenId == JsTokenId.BLOCK_COMMENT || currentTokenId == JsTokenId.DOC_COMMENT
                || currentTokenId == JsTokenId.LINE_COMMENT) {
            if (lastChar == '@') { //NOI18N
                return QueryType.COMPLETION;
            }
        } else if (currentTokenId == JsTokenId.STRING && lastChar == '/') {
            return QueryType.COMPLETION;
        } else {
            switch (lastChar) {
            case '.': //NOI18N
                if (OptionsUtils.forLanguage(JsTokenId.javascriptLanguage()).autoCompletionAfterDot()) {
                    return QueryType.COMPLETION;
                }
                break;
            default:
                if (OptionsUtils.forLanguage(JsTokenId.javascriptLanguage()).autoCompletionFull()) {
                    if (!Character.isWhitespace(lastChar) && CHARS_NO_AUTO_COMPLETE.indexOf(lastChar) == -1) {
                        return QueryType.COMPLETION;
                    }
                }
                return QueryType.NONE;
            }
        }
    }
    return QueryType.NONE;
}

From source file:org.executequery.gui.editor.autocomplete.QueryEditorAutoCompletePopupProvider.java

public void popupSelectionMade() {

    AutoCompleteListItem selectedListItem = (AutoCompleteListItem) autoCompletePopup.getSelectedItem();

    if (selectedListItem == null || selectedListItem.isNothingProposed()) {

        return;/* www  . j  av a2 s .  c  o  m*/
    }

    String selectedValue = selectedListItem.getInsertionValue();

    try {

        JTextComponent textComponent = queryEditorTextComponent();
        Document document = textComponent.getDocument();

        int caretPosition = textComponent.getCaretPosition();
        String wordAtCursor = queryEditor.getWordToCursor();

        if (StringUtils.isNotBlank(wordAtCursor)) {

            int wordAtCursorLength = wordAtCursor.length();
            int insertionIndex = caretPosition - wordAtCursorLength;

            if (selectedListItem.isKeyword() && isAllLowerCase(wordAtCursor)) {

                selectedValue = selectedValue.toLowerCase();
            }

            if (!Character.isLetterOrDigit(wordAtCursor.charAt(0))) {

                // cases where you might have a.column_name or similar

                insertionIndex++;
                wordAtCursorLength--;

            } else if (wordAtCursor.contains(".")) {

                int index = wordAtCursor.indexOf(".");
                insertionIndex += index + 1;
                wordAtCursorLength -= index + 1;
            }

            document.remove(insertionIndex, wordAtCursorLength);
            document.insertString(insertionIndex, selectedValue, null);

        } else {

            document.insertString(caretPosition, selectedValue, null);
        }

    } catch (BadLocationException e) {

        debug("Error on autocomplete insertion", e);

    } finally {

        autoCompletePopup.hidePopup();
    }

}

From source file:org.executequery.gui.text.TextUtilities.java

public static void deleteLine(JTextComponent textComponent) {
    char newLine = '\n';
    String _newLine = "\n";
    int caretIndex = textComponent.getCaretPosition();

    String text = textComponent.getText();
    StringBuilder sb = new StringBuilder(text);

    int endOfLineIndexBefore = -1;
    int endOfLineIndexAfter = sb.indexOf(_newLine, caretIndex);

    char[] textChars = text.toCharArray();

    for (int i = 0; i < textChars.length; i++) {

        if (i >= caretIndex) {
            break;
        } else {/*from w w  w. j  a v  a  2  s. c  o  m*/

            if (textChars[i] == newLine)
                endOfLineIndexBefore = i;

        }

    }

    if (endOfLineIndexBefore == -1) {
        endOfLineIndexBefore = 0;
    }

    if (endOfLineIndexAfter == -1) {
        sb.delete(endOfLineIndexBefore, sb.length());
    } else if (endOfLineIndexBefore == -1) {
        sb.delete(0, endOfLineIndexAfter + 1);
    } else if (endOfLineIndexBefore == 0 && endOfLineIndexAfter == 0) {
        sb.deleteCharAt(0);
    } else {
        sb.delete(endOfLineIndexBefore, endOfLineIndexAfter);
    }

    textComponent.setText(sb.toString());

    if (endOfLineIndexBefore + 1 > sb.length()) {

        textComponent.setCaretPosition(endOfLineIndexBefore == -1 ? 0 : endOfLineIndexBefore);

    } else {

        textComponent.setCaretPosition(endOfLineIndexBefore + 1);
    }

}