Example usage for javax.swing.text JTextComponent setText

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

Introduction

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

Prototype

@BeanProperty(bound = false, description = "the text of this component")
public void setText(String t) 

Source Link

Document

Sets the text of this TextComponent to the specified text.

Usage

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;/*from w  w w  .j  a 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 w w. jav  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:openlr.mapviewer.coding.ui.AbstractCodingOptionsDialog.java

/**
 * Sets the values in the input form according to the given configuration.
 * //from  ww w .j  a v a  2s  . c  o m
 * @param config
 *            The configuration that provides the values to display
 */
void setValues(final FileConfiguration config) {
    for (Map.Entry<String, JTextComponent> entry : optionsTextFields.entrySet()) {

        JTextComponent textComponent = entry.getValue();
        textComponent.setText(config.getString(entry.getKey()));
    }
}

From source file:org.apache.cayenne.modeler.util.PathChooserComboBoxCellEditor.java

protected void processDotEntered() {
    JTextComponent editorComponent = (JTextComponent) (comboBoxPathChooser).getEditor().getEditorComponent();

    String dbAttributePath = editorComponent.getText();
    if (".".equals(dbAttributePath)) {
        setComboModelAccordingToPath("");
        return;/*from   www. j a  v  a 2  s . c  om*/
    }
    char secondFromEndCharacter = dbAttributePath.charAt(dbAttributePath.length() - 2);
    if (secondFromEndCharacter == '.') {
        // two dots entered one by one , we replace it by one dot
        editorComponent.setText(dbAttributePath.substring(0, dbAttributePath.length() - 1));
        return;
    }
    String[] pathStrings = dbAttributePath.split(Pattern.quote("."));
    String lastStringInPath = pathStrings[pathStrings.length - 1];

    //we will check if lastStringInPath is correct name of DbAttribute or DbRelationship
    //for appropriate previous node in path. if it is not we won't add entered dot to dbAttributePath
    String dbAttributePathForPreviousNode;
    if (pathStrings.length == 1) {
        //previous root is treeModel.getRoot()
        dbAttributePathForPreviousNode = "";
    } else {
        dbAttributePathForPreviousNode = dbAttributePath.replaceAll('.' + lastStringInPath + ".$", "");
    }
    List<String> potentialVariantsToChoose = getChildren(getCurrentNode(dbAttributePathForPreviousNode), "");
    if (potentialVariantsToChoose.contains(lastStringInPath)
            && !(getCurrentNode(dbAttributePath) instanceof DbAttribute)) {
        setComboModelAccordingToPath(dbAttributePath);
    } else {
        editorComponent.setText(dbAttributePath.substring(0, dbAttributePath.length() - 1));
    }
}

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 {/*w w w  .j a va2  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);
    }

}

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

public static void deleteWord(JTextComponent textComponent) {
    char space = ' ';
    String _space = " ";
    int caretIndex = textComponent.getCaretPosition();

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

    int startOfWordIndex = -1;
    int endOfWordIndex = sb.indexOf(_space, caretIndex);

    char[] textChars = text.toCharArray();

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

        if (i >= caretIndex) {
            break;
        }//w ww.  j  a  va 2s .  com

        else {

            if (textChars[i] == space)
                startOfWordIndex = i;

        }

    }

    if (endOfWordIndex == -1)
        return;

    else if (startOfWordIndex == 0 && endOfWordIndex == 0)
        return;

    else if (startOfWordIndex == endOfWordIndex)
        return;

    sb.delete(startOfWordIndex + 1, endOfWordIndex);
    textComponent.setText(sb.toString());
    textComponent.setCaretPosition(startOfWordIndex + 1);
}

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

public static void insertFromFile(JTextComponent textComponent) {
    StringBuffer buf = null;/*from w w w.  j a va2 s . co  m*/
    String text = null;

    FileChooserDialog fileChooser = new FileChooserDialog();
    fileChooser.setDialogTitle("Insert from file");
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
    int result = fileChooser.showDialog(GUIUtilities.getInFocusDialogOrWindow(), "Insert");

    if (result == JFileChooser.CANCEL_OPTION)
        return;

    File file = fileChooser.getSelectedFile();

    try {
        FileInputStream input = new FileInputStream(file);
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        buf = new StringBuffer(10000);

        char newLine = '\n';

        while ((text = reader.readLine()) != null)
            buf.append(text).append(newLine);

        reader.close();
        reader = null;
        input.close();
        input = null;

        int index = textComponent.getCaretPosition();
        StringBuffer sb = new StringBuffer(textComponent.getText());
        sb.insert(index, buf.toString());
        textComponent.setText(sb.toString());
        textComponent.setCaretPosition(index + buf.length());

    } catch (OutOfMemoryError e) {
        buf = null;
        text = null;
        System.gc();
        GUIUtilities.displayErrorMessage("Out of Memory.\nThe file is " + "too large to\nopen for viewing.");
    } catch (IOException e) {
        e.printStackTrace();
        StringBuffer sb = new StringBuffer();
        sb.append("An error occurred opening the selected file.").append("\n\nThe system returned:\n")
                .append(e.getMessage());
        GUIUtilities.displayExceptionErrorDialog(sb.toString(), e);
    }

}

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

public static void insertLineAfter(JTextComponent textComponent) {
    String newLine = "\n";
    int caretIndex = textComponent.getCaretPosition();

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

    int endOfLineIndex = sb.indexOf(newLine, caretIndex);

    int length = sb.length();

    if (caretIndex == length || endOfLineIndex == length)
        sb.append(newLine);//from  w ww. j  a va  2  s . co  m
    else
        sb.insert(endOfLineIndex == -1 ? 0 : endOfLineIndex, newLine);

    textComponent.setText(sb.toString());
    textComponent.setCaretPosition(endOfLineIndex == -1 ? length : endOfLineIndex + 1);
    sb = null;
}

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

public static void insertLineBefore(JTextComponent textComponent) {
    int caretIndex = textComponent.getCaretPosition();
    int insertIndex = -1;
    char newLine = '\n';

    String text = textComponent.getText();
    char[] textChars = text.toCharArray();

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

        if (i > caretIndex) {
            break;
        }//from  w w w . j av a 2s.  c om

        else {

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

        }

    }

    StringBuilder sb = new StringBuilder(text);
    sb.insert(insertIndex == -1 ? 0 : insertIndex, newLine);

    textComponent.setText(sb.toString());
    textComponent.setCaretPosition(insertIndex + 1);
}

From source file:org.isatools.isacreator.gui.DataEntryForm.java

public JComponent createFileField(final JTextComponent field) {
    final FileChooserUI fileChooserUI = new FileChooserUI();
    final DropDownComponent dropdown = new DropDownComponent(field, fileChooserUI, DropDownComponent.FILE);

    fileChooserUI.addPropertyChangeListener("selectedFiles", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
            String contents = "";
            int count = 0;

            for (String file : fileChooserUI.getSelectedFiles()) {
                contents += file;//from w  ww.ja va2 s.c o m
                if (count != fileChooserUI.getSelectedFiles().length - 1) {
                    contents += ",";
                }
                count++;
            }
            field.setText(contents);
            dropdown.hidePopup(fileChooserUI);
        }
    });

    fileChooserUI.addPropertyChangeListener("noSelectedFiles", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
            dropdown.hidePopup(fileChooserUI);
        }
    });

    return dropdown;

}