Example usage for javax.swing.text JTextComponent replaceSelection

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

Introduction

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

Prototype

public void replaceSelection(String content) 

Source Link

Document

Replaces the currently selected content with new content represented by the given string.

Usage

From source file:Main.java

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

    c.replaceSelection("replacement text");
}

From source file:DragColorTextFieldDemo.java

public boolean importData(JComponent c, Transferable t) {
    JTextComponent tc = (JTextComponent) c;

    if (!canImport(c, t.getTransferDataFlavors())) {
        return false;
    }/*from w w w.jav a  2s  .  com*/

    if (tc.equals(source) && (tc.getCaretPosition() >= p0.getOffset())
            && (tc.getCaretPosition() <= p1.getOffset())) {
        shouldRemove = false;
        return true;
    }

    if (hasStringFlavor(t.getTransferDataFlavors())) {
        try {
            String str = (String) t.getTransferData(stringFlavor);
            tc.replaceSelection(str);
            return true;
        } catch (UnsupportedFlavorException ufe) {
            System.out.println("importData: unsupported data flavor");
        } catch (IOException ioe) {
            System.out.println("importData: I/O exception");
        }
    }
    //The ColorTransferHandler superclass handles color.
    return super.importData(c, t);
}

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

/**
 * If user cancels autocompletion by//  www  . j a v  a  2s  .  co m
 *   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

@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;/*  ww  w  . ja v a 2  s  .c om*/
    }

    // 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 ww. j  a v  a  2s. 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:org.executequery.gui.text.TextUtilities.java

public static void changeSelectionToCamelCase(JTextComponent textComponent) {

    String selectedText = textComponent.getSelectedText();
    if (StringUtils.isBlank(selectedText)) {

        return;//from ww  w.  j a  v a 2 s  .  com
    }

    String breakChars = "-_ \t";

    boolean nextIsUpper = false;
    StringBuilder sb = new StringBuilder();
    char[] chars = selectedText.toCharArray();
    for (int i = 0; i < chars.length; i++) {

        char _char = chars[i];
        if (breakChars.indexOf(_char) != -1) {

            if (i > 0) {

                nextIsUpper = true;
            }

        } else {

            if (nextIsUpper) {

                sb.append(Character.toUpperCase(_char));
                nextIsUpper = false;

            } else {

                sb.append(Character.toLowerCase(_char));
            }
        }
    }

    textComponent.replaceSelection(sb.toString());
}

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

public static void changeSelectionToUnderscore(JTextComponent textComponent) {

    String selectedText = textComponent.getSelectedText();
    if (StringUtils.isBlank(selectedText)) {

        return;//  ww  w.  j a  v  a2s .  co  m
    }

    String breakChars = "-_ \t";

    boolean lastCharWasUnderscore = false;
    StringBuilder sb = new StringBuilder();
    char[] chars = selectedText.toCharArray();
    for (int i = 0; i < chars.length; i++) {

        char _char = chars[i];
        if (breakChars.indexOf(_char) != -1) {

            sb.append("_");
            lastCharWasUnderscore = true;

        } else if (Character.isUpperCase(_char)) {

            if (!lastCharWasUnderscore) {

                sb.append("_");
            }
            sb.append(_char);
            lastCharWasUnderscore = false;

        } else {

            sb.append(_char);
            lastCharWasUnderscore = false;
        }

    }

    textComponent.replaceSelection(sb.toString().toLowerCase());
}

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

public static void changeSelectionCase(JTextComponent textComponent, boolean upper) {

    String selectedText = textComponent.getSelectedText();
    if (StringUtils.isBlank(selectedText)) {

        return;/*  ww w  . j  a  v  a  2s.c om*/
    }

    if (upper) {
        selectedText = selectedText.toUpperCase();

    } else {

        selectedText = selectedText.toLowerCase();
    }
    textComponent.replaceSelection(selectedText);

}

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

public static void deleteSelection(JTextComponent textComponent) {
    textComponent.replaceSelection("");
}

From source file:org.fife.ui.rtextarea.RTATextTransferHandler.java

/**
 * Import the given stream data into the text component.
 *//* w  ww. j a  v  a 2  s .c  om*/
protected void handleReaderImport(Reader in, JTextComponent c) throws BadLocationException, IOException {
    if (withinSameComponent) {
        ((RTextArea) c).beginAtomicEdit();
    }

    c.replaceSelection(IOUtils.toString(in));
}