Example usage for javax.swing.text JTextComponent select

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

Introduction

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

Prototype

public void select(int selectionStart, int selectionEnd) 

Source Link

Document

Selects the text between the specified start and end positions.

Usage

From source file:Main.java

public static void main(String[] argv) {
    JTextComponent c = new JTextArea();

    c.select(10, 20);
}

From source file:net.sf.jabref.gui.keyboard.EmacsKeyBindings.java

private static void doCopyOrCut(JTextComponent jtc, boolean copy) {
    if (jtc != null) {
        int caretPosition = jtc.getCaretPosition();
        String text = jtc.getSelectedText();
        if (text != null) {
            // user has manually marked a text without using CTRL+W
            // we obey that selection and copy it.
        } else if (SetMarkCommandAction.isMarked(jtc)) {
            int beginPos = caretPosition;
            int endPos = SetMarkCommandAction.getCaretPosition();
            if (beginPos > endPos) {
                int tmp = endPos;
                endPos = beginPos;/*  w  w w  .  j a  v  a 2s.co  m*/
                beginPos = tmp;
            }
            jtc.select(beginPos, endPos);
            SetMarkCommandAction.reset();
        }
        text = jtc.getSelectedText();
        if (text == null) {
            jtc.getToolkit().beep();
        } else {
            if (copy) {
                jtc.copy();
                // clear the selection
                jtc.select(caretPosition, caretPosition);
            } else {
                int newCaretPos = jtc.getSelectionStart();
                jtc.cut();
                // put the cursor to the beginning of the text to cut
                jtc.setCaretPosition(newCaretPos);
            }
            KillRing.getInstance().add(text);
        }
    }
}

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

@Override
public void keyPressed(KeyEvent e) {
    if ((toSetIn != null) && (e.getKeyCode() == KeyEvent.VK_ENTER)) {
        JTextComponent comp = (JTextComponent) e.getSource();

        // replace typed characters by characters from completion
        lastBeginning = lastCompletions.get(lastShownCompletion);

        int end = comp.getSelectionEnd();
        comp.select(end, end);
        toSetIn = null;//w ww. j a  v  a  2s  . com
        if (consumeEnterKey) {
            e.consume();
        }
    }
    // Cycle through alternative completions when user presses PGUP/PGDN:
    else if ((e.getKeyCode() == KeyEvent.VK_PAGE_DOWN) && (toSetIn != null)) {
        cycle((JTextComponent) e.getSource(), 1);
        e.consume();
    } else if ((e.getKeyCode() == KeyEvent.VK_PAGE_UP) && (toSetIn != null)) {
        cycle((JTextComponent) e.getSource(), -1);
        e.consume();
    }
    //        else if ((e.getKeyCode() == KeyEvent.VK_BACK_SPACE)) {
    //           StringBuffer currentword = getCurrentWord((JTextComponent) e.getSource());
    //           // delete last char to obey semantics of back space
    //           currentword.deleteCharAt(currentword.length()-1);
    //           doCompletion(currentword, e);
    //        }
    else if (e.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
        if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
            // shift is OK, everything else leads to a reset
            LOGGER.debug("Special case: shift pressed. No action.");
        } else {
            resetAutoCompletion();
        }
    } else {
        LOGGER.debug("Special case: defined character, but not caught above");
    }
}

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

@Override
public void keyPressed(KeyEvent e) {
    if ((toSetIn != null) && (e.getKeyCode() == KeyEvent.VK_ENTER)) {
        JTextComponent comp = (JTextComponent) e.getSource();

        // replace typed characters by characters from completion
        lastBeginning = lastCompletions[lastShownCompletion];

        int end = comp.getSelectionEnd();
        comp.select(end, end);
        toSetIn = null;/*from w  w w  .j  ava 2s . c o m*/
        if (consumeEnterKey) {
            e.consume();
        }
    }
    // Cycle through alternative completions when user presses PGUP/PGDN:
    else if ((e.getKeyCode() == KeyEvent.VK_PAGE_DOWN) && (toSetIn != null)) {
        cycle((JTextComponent) e.getSource(), 1);
        e.consume();
    } else if ((e.getKeyCode() == KeyEvent.VK_PAGE_UP) && (toSetIn != null)) {
        cycle((JTextComponent) e.getSource(), -1);
        e.consume();
    }
    //        else if ((e.getKeyCode() == KeyEvent.VK_BACK_SPACE)) {
    //           StringBuffer currentword = getCurrentWord((JTextComponent) e.getSource());
    //           // delete last char to obey semantics of back space
    //           currentword.deleteCharAt(currentword.length()-1);
    //           doCompletion(currentword, e);
    //        }
    else if (e.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
        if (e.getKeyCode() != KeyEvent.VK_SHIFT) {
            // shift is OK, everyhting else leads to a reset
            resetAutoCompletion();
        } else {
            LOGGER.debug("Special case: shift pressed. No action.");
        }
    } else {
        LOGGER.debug("Special case: defined character, but not caught above");
    }
}

From source file:com.mindcognition.mindraider.ui.swing.concept.annotation.renderer.AbstractTextAnnotationRenderer.java

/**
 * Search annotation from the current carret position.
 *//*from   w  ww.  j av  a  2  s  .  c  o  m*/
public void searchAnnotation(String searchString, boolean again) {
    logger.debug("searchAnnotation() " + searchString); // {{debug}}
    JTextComponent textComponent;
    if (inViewMode()) {
        textComponent = viewer;
        logger.debug("Searching viewer..."); // {{debug}}
    } else {
        textComponent = editor;
        logger.debug("Searching editor..."); // {{debug}}
    }

    if (!again) {
        textComponent.setCaretPosition(0);
    }

    if (searchString != null && searchString.length() > 0) {
        Document document = textComponent.getDocument();
        try {
            int idx = textComponent.getDocument().getText(0, document.getLength()).indexOf(searchString,
                    textComponent.getCaretPosition());
            if (idx < 0) {
                // try it from the beginning
                idx = textComponent.getDocument().getText(0, document.getLength()).indexOf(searchString);
            } else if (idx > 0) {
                textComponent.setCaretPosition(idx);
                textComponent.requestFocus();
                textComponent.select(idx, idx + searchString.length());
            }
        } catch (Exception e) {
            // TODO no bundle!
            logger.debug(Messages.getString("ConceptJPanel.unableToSearch", e.getMessage()));
        }
    }
}

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

@Override
public void keyTyped(KeyEvent e) {
    LOGGER.debug("key typed event caught " + e.getKeyCode());
    char ch = e.getKeyChar();
    if (ch == '\n') {
        // this case is handled at keyPressed(e)
        return;//  w ww  .  ja v  a2  s.c o  m
    }

    // don't do auto completion inside words
    if (!atEndOfWord((JTextComponent) e.getSource())) {
        return;
    }

    if ((e.getModifiers() | InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) {
        // plain key or SHIFT + key is pressed, no handling of CTRL+key,  META+key, ...
        if (Character.isLetter(ch) || Character.isDigit(ch)
                || (Character.isWhitespace(ch) && completer.isSingleUnitField())) {
            JTextComponent comp = (JTextComponent) e.getSource();

            if (toSetIn == null) {
                LOGGER.debug("toSetIn is null");
            } else {
                LOGGER.debug("toSetIn: >" + toSetIn + '<');
            }

            // The case-insensitive system is a bit tricky here
            // If keyword is "TODO" and user types "tO", then this is treated as "continue" as the "O" matches the "O"
            // If keyword is "TODO" and user types "To", then this is treated as "discont" as the "o" does NOT match the "O".

            if ((toSetIn != null) && (toSetIn.length() > 1) && (ch == toSetIn.charAt(1))) {
                // User continues on the word that was suggested.
                LOGGER.debug("cont");

                toSetIn = toSetIn.substring(1);
                if (!toSetIn.isEmpty()) {
                    int cp = comp.getCaretPosition();
                    //comp.setCaretPosition(cp+1-toSetIn.);
                    comp.select((cp + 1) - toSetIn.length(), cp);
                    lastBeginning = lastBeginning + ch;

                    e.consume();
                    lastCaretPosition = comp.getCaretPosition();

                    lastCompletions = findCompletions(lastBeginning);
                    lastShownCompletion = 0;
                    for (int i = 0; i < lastCompletions.size(); i++) {
                        String lastCompletion = lastCompletions.get(i);
                        if (lastCompletion.endsWith(toSetIn)) {
                            lastShownCompletion = i;
                            break;
                        }

                    }
                    if (toSetIn.length() < 2) {
                        // User typed the last character of the autocompleted word
                        // We have to replace the automcompletion word by the typed word.
                        // This helps if the user presses "space" after the completion
                        // "space" indicates that the user does NOT want the autocompletion,
                        // but the typed word
                        String text = comp.getText();
                        comp.setText(text.substring(0, lastCaretPosition - lastBeginning.length())
                                + lastBeginning + text.substring(lastCaretPosition));
                        // there is no selected text, therefore we are not updating the selection
                        toSetIn = null;
                    }
                    return;
                }
            }

            if ((toSetIn != null) && ((toSetIn.length() <= 1) || (ch != toSetIn.charAt(1)))) {
                // User discontinues the word that was suggested.
                lastBeginning = lastBeginning + ch;

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

                List<String> completed = findCompletions(lastBeginning);
                if ((completed != null) && (!completed.isEmpty())) {
                    lastShownCompletion = 0;
                    lastCompletions = completed;
                    String sno = completed.get(0);
                    // toSetIn = string used for autocompletion last time
                    // this string has to be removed
                    // lastCaretPosition is the position of the caret after toSetIn.
                    int lastLen = toSetIn.length() - 1;
                    toSetIn = sno.substring(lastBeginning.length() - 1);
                    String text = comp.getText();
                    //we do not use toSetIn as we want to obey the casing of "sno"
                    comp.setText(text.substring(0, (lastCaretPosition - lastLen - lastBeginning.length()) + 1)
                            + sno + text.substring(lastCaretPosition));
                    int startSelect = (lastCaretPosition + 1) - lastLen;
                    int endSelect = (lastCaretPosition + toSetIn.length()) - lastLen;
                    comp.select(startSelect, endSelect);

                    lastCaretPosition = comp.getCaretPosition();
                    e.consume();
                    return;
                } else {
                    setUnmodifiedTypedLetters(comp, true, false);
                    e.consume();
                    toSetIn = null;
                    return;
                }
            }

            LOGGER.debug("case else");

            comp.replaceSelection("");

            StringBuffer currentword = getCurrentWord(comp);

            // only "real characters" end up here
            assert (!Character.isISOControl(ch));
            currentword.append(ch);
            startCompletion(currentword, e);
            return;
        } else {
            if (Character.isWhitespace(ch)) {
                assert (!completer.isSingleUnitField());
                LOGGER.debug("whitespace && !singleUnitField");
                // start a new search if end-of-field is reached

                // replace displayed letters with typed letters
                setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, true);
                resetAutoCompletion();
                return;
            }

            LOGGER.debug("No letter/digit/whitespace or CHAR_UNDEFINED");
            // replace displayed letters with typed letters
            setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, !Character.isISOControl(ch));
            resetAutoCompletion();
            return;
        }
    }
    resetAutoCompletion();
}

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

@Override
public void keyTyped(KeyEvent e) {
    LOGGER.debug("key typed event caught " + e.getKeyCode());
    char ch = e.getKeyChar();
    if (ch == '\n') {
        // this case is handled at keyPressed(e)
        return;//  w  w  w  . ja v  a  2  s  . c o m
    }

    if ((e.getModifiers() | InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) {
        // plain key or SHIFT + key is pressed, no handling of CTRL+key,  META+key, ...
        if (Character.isLetter(ch) || Character.isDigit(ch)
                || (Character.isWhitespace(ch) && completer.isSingleUnitField())) {
            JTextComponent comp = (JTextComponent) e.getSource();

            if (toSetIn == null) {
                LOGGER.debug("toSetIn is null");
            } else {
                LOGGER.debug("toSetIn: >" + toSetIn + '<');
            }

            // The case-insensitive system is a bit tricky here
            // If keyword is "TODO" and user types "tO", then this is treated as "continue" as the "O" matches the "O"
            // If keyword is "TODO" and user types "To", then this is treated as "discont" as the "o" does NOT match the "O".

            if ((toSetIn != null) && (toSetIn.length() > 1) && (ch == toSetIn.charAt(1))) {
                // User continues on the word that was suggested.
                LOGGER.debug("cont");

                toSetIn = toSetIn.substring(1);
                if (!toSetIn.isEmpty()) {
                    int cp = comp.getCaretPosition();
                    //comp.setCaretPosition(cp+1-toSetIn.);
                    //System.out.println(cp-toSetIn.length()+" - "+cp);
                    comp.select((cp + 1) - toSetIn.length(), cp);
                    lastBeginning = lastBeginning + ch;

                    e.consume();
                    lastCaretPosition = comp.getCaretPosition();

                    //System.out.println("Added char: '"+toSetIn+"'");
                    //System.out.println("LastBeginning: '"+lastBeginning+"'");

                    lastCompletions = findCompletions(lastBeginning, comp);
                    lastShownCompletion = 0;
                    for (int i = 0; i < lastCompletions.length; i++) {
                        String lastCompletion = lastCompletions[i];
                        //System.out.println("Completion["+i+"] = "+lastCompletion);
                        if (lastCompletion.endsWith(toSetIn)) {
                            lastShownCompletion = i;
                            break;
                        }

                    }
                    //System.out.println("Index now: "+lastShownCompletion);
                    if (toSetIn.length() < 2) {
                        // User typed the last character of the autocompleted word
                        // We have to replace the automcompletion word by the typed word.
                        // This helps if the user presses "space" after the completion
                        // "space" indicates that the user does NOT want the autocompletion,
                        // but the typed word
                        String text = comp.getText();
                        comp.setText(text.substring(0, lastCaretPosition - lastBeginning.length())
                                + lastBeginning + text.substring(lastCaretPosition));
                        // there is no selected text, therefore we are not updating the selection
                        toSetIn = null;
                    }
                    return;
                }
            }

            if ((toSetIn != null) && ((toSetIn.length() <= 1) || (ch != toSetIn.charAt(1)))) {
                // User discontinues the word that was suggested.
                lastBeginning = lastBeginning + ch;

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

                String[] completed = findCompletions(lastBeginning, comp);
                if ((completed != null) && (completed.length > 0)) {
                    lastShownCompletion = 0;
                    lastCompletions = completed;
                    String sno = completed[0];
                    // toSetIn = string used for autocompletion last time
                    // this string has to be removed
                    // lastCaretPosition is the position of the caret after toSetIn.
                    int lastLen = toSetIn.length() - 1;
                    toSetIn = sno.substring(lastBeginning.length() - 1);
                    String text = comp.getText();
                    //Util.pr(""+lastLen);
                    //we do not use toSetIn as we want to obey the casing of "sno"
                    comp.setText(text.substring(0, (lastCaretPosition - lastLen - lastBeginning.length()) + 1)
                            + sno + text.substring(lastCaretPosition));
                    int startSelect = (lastCaretPosition + 1) - lastLen;
                    int endSelect = (lastCaretPosition + toSetIn.length()) - lastLen;
                    comp.select(startSelect, endSelect);

                    lastCaretPosition = comp.getCaretPosition();
                    e.consume();
                    return;
                } else {
                    setUnmodifiedTypedLetters(comp, true, false);
                    e.consume();
                    toSetIn = null;
                    return;
                }
            }

            LOGGER.debug("case else");

            comp.replaceSelection("");

            StringBuffer currentword = getCurrentWord(comp);
            if (currentword == null) {
                currentword = new StringBuffer();
            }

            // only "real characters" end up here
            assert (!Character.isISOControl(ch));
            currentword.append(ch);
            startCompletion(currentword, e);
            return;
        } else {
            if (Character.isWhitespace(ch)) {
                assert (!completer.isSingleUnitField());
                LOGGER.debug("whitespace && !singleUnitField");
                // start a new search if end-of-field is reached

                // replace displayed letters with typed letters
                setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, true);
                resetAutoCompletion();
                return;
            }

            LOGGER.debug("No letter/digit/whitespace or CHAR_UNDEFINED");
            // replace displayed letters with typed letters 
            setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, !Character.isISOControl(ch));
            resetAutoCompletion();
            return;
        }
    }
    resetAutoCompletion();
}

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  a va2s  .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  ww w.ja va 2  s. c om*/
    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: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)//ww  w . java  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));
        }
    }

}