Example usage for javax.swing.text JTextComponent setCaretPosition

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

Introduction

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

Prototype

@BeanProperty(bound = false, description = "the caret position")
public void setCaretPosition(int position) 

Source Link

Document

Sets the position of the text insertion caret for the TextComponent.

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 ava2 s .c om*/
 */
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// w w w.j a  va2  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 ava2s .  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:edu.ku.brc.ui.tmanfe.SpreadSheet.java

/**
  * // w w  w .  j a v a 2  s  .c  o m
  */
protected void buildSpreadsheet() {

    this.setShowGrid(true);

    int numRows = model.getRowCount();

    scrollPane = new JScrollPane(this, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    final SpreadSheet ss = this;
    JButton cornerBtn = UIHelper.createIconBtn("Blank", IconManager.IconSize.Std16, "SelectAll",
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    ss.selectAll();
                }
            });
    cornerBtn.setEnabled(true);
    scrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, cornerBtn);

    // Allows row and collumn selections to exit at the same time
    setCellSelectionEnabled(true);

    setRowSelectionAllowed(true);
    setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    addMouseListener(new MouseAdapter() {
        /* (non-Javadoc)
         * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
         */
        @SuppressWarnings("synthetic-access")
        @Override
        public void mouseReleased(MouseEvent e) {
            // XXX For Java 5 Bug
            prevRowSelInx = getSelectedRow();
            prevColSelInx = getSelectedColumn();

            if (e.getClickCount() == 2) {
                int rowIndexStart = getSelectedRow();
                int colIndexStart = getSelectedColumn();

                ss.editCellAt(rowIndexStart, colIndexStart);
                if (ss.getEditorComponent() != null && ss.getEditorComponent() instanceof JTextComponent) {
                    ss.getEditorComponent().requestFocus();

                    final JTextComponent txtComp = (JTextComponent) ss.getEditorComponent();
                    String txt = txtComp.getText();
                    FontMetrics fm = txtComp.getFontMetrics(txtComp.getFont());
                    int x = e.getPoint().x - ss.getEditorComponent().getBounds().x - 1;
                    int prevWidth = 0;
                    for (int i = 0; i < txt.length(); i++) {

                        int width = fm.stringWidth(txt.substring(0, i));
                        int basePlusHalf = prevWidth + (int) (((width - prevWidth) / 2) + 0.5);
                        //System.out.println(prevWidth + " X[" + x + "] " + width+" ["+txt.substring(0, i)+"] " + i + " " + basePlusHalf);
                        //System.out.println(" X[" + x + "] " + prevWidth + " - "+ basePlusHalf+" - " + width+" ["+txt.substring(0, i)+"] " + i);
                        if (x < width) {
                            // Clearing the selection is needed for Window for some reason
                            final int inx = i + (x <= basePlusHalf ? -1 : 0);
                            SwingUtilities.invokeLater(new Runnable() {
                                @SuppressWarnings("synthetic-access")
                                public void run() {
                                    txtComp.setSelectionStart(0);
                                    txtComp.setSelectionEnd(0);
                                    txtComp.setCaretPosition(inx > 0 ? inx : 0);
                                }
                            });
                            break;
                        }
                        prevWidth = width;
                    }
                }
            }
        }
    });

    // Create a row-header to display row numbers.
    // This row-header is made of labels whose Borders,
    // Foregrounds, Backgrounds, and Fonts must be
    // the one used for the table column headers.
    // Also ensure that the row-header labels and the table
    // rows have the same height.

    //i have no idea WHY this has to be called.  i rearranged
    //the table and find replace panel, 
    // i started getting an array index out of
    //bounds on the column header ON MAC ONLY.  
    //tried firing this off, first and it fixed the problem.//meg
    this.getModel().fireTableStructureChanged();

    /*
     * Create the Row Header Panel
     */
    rowHeaderPanel = new JPanel((LayoutManager) null);

    if (getColumnModel().getColumnCount() > 0) {
        TableColumn column = getColumnModel().getColumn(0);
        TableCellRenderer renderer = getTableHeader().getDefaultRenderer();
        if (renderer == null) {
            renderer = column.getHeaderRenderer();
        }

        Component cellRenderComp = renderer.getTableCellRendererComponent(this, column.getHeaderValue(), false,
                false, -1, 0);
        cellFont = cellRenderComp.getFont();

    } else {
        cellFont = (new JLabel()).getFont();
    }

    // Calculate Row Height
    cellBorder = (Border) UIManager.getDefaults().get("TableHeader.cellBorder");
    Insets insets = cellBorder.getBorderInsets(tableHeader);
    FontMetrics metrics = getFontMetrics(cellFont);

    rowHeight = insets.bottom + metrics.getHeight() + insets.top;
    rowLabelWidth = metrics.stringWidth("9999") + insets.right + insets.left;

    Dimension dim = new Dimension(rowLabelWidth, rowHeight * numRows);
    rowHeaderPanel.setPreferredSize(dim); // need to call this when no layout manager is used.

    rhCellMouseAdapter = new RHCellMouseAdapter(this);

    // Adding the row header labels
    for (int ii = 0; ii < numRows; ii++) {
        addRow(ii, ii + 1, false);
    }

    JViewport viewPort = new JViewport();
    dim.height = rowHeight * numRows;
    viewPort.setViewSize(dim);
    viewPort.setView(rowHeaderPanel);
    scrollPane.setRowHeader(viewPort);

    // Experimental from the web, but I think it does the trick.
    addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (!ss.isEditing() && !e.isActionKey() && !e.isControlDown() && !e.isMetaDown() && !e.isAltDown()
                    && e.getKeyCode() != KeyEvent.VK_SHIFT && e.getKeyCode() != KeyEvent.VK_TAB
                    && e.getKeyCode() != KeyEvent.VK_ENTER) {
                log.error("Grabbed the event as input");

                int rowIndexStart = getSelectedRow();
                int colIndexStart = getSelectedColumn();

                if (rowIndexStart == -1 || colIndexStart == -1)
                    return;

                ss.editCellAt(rowIndexStart, colIndexStart);
                Component c = ss.getEditorComponent();
                if (c instanceof JTextComponent)
                    ((JTextComponent) c).setText("");
            }
        }
    });

    resizeAndRepaint();

    // Taken from a JavaWorld Example (But it works)
    KeyStroke cut = KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
            false);
    KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
            false);
    KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false);

    Action ssAction = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SpreadSheet.this.actionPerformed(e);
        }
    };

    getInputMap().put(cut, "Cut");
    getActionMap().put("Cut", ssAction);

    getInputMap().put(copy, "Copy");
    getActionMap().put("Copy", ssAction);

    getInputMap().put(paste, "Paste");
    getActionMap().put("Paste", ssAction);

    ((JMenuItem) UIRegistry.get(UIRegistry.COPY)).addActionListener(this);
    ((JMenuItem) UIRegistry.get(UIRegistry.CUT)).addActionListener(this);
    ((JMenuItem) UIRegistry.get(UIRegistry.PASTE)).addActionListener(this);

    setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED);
}

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

/**
 * Method for finding (and optionally replacing) a string in the text
 *///from  ww w  .  j av a  2  s.  co m
private int findText(String findTerm, String replaceTerm, boolean bCaseSenstive, int iOffset) {
    JTextComponent jtpFindSource;
    if (sourceWindowActive || jtpSource.hasFocus()) {
        jtpFindSource = (JTextComponent) jtpSource;
    } else {
        jtpFindSource = (JTextComponent) jtpMain;
    }
    int searchPlace = -1;
    try {
        Document baseDocument = jtpFindSource.getDocument();
        searchPlace = (bCaseSenstive
                ? baseDocument.getText(0, baseDocument.getLength()).indexOf(findTerm, iOffset)
                : baseDocument.getText(0, baseDocument.getLength()).toLowerCase()
                        .indexOf(findTerm.toLowerCase(), iOffset));
        if (searchPlace > -1) {
            if (replaceTerm != null) {
                AttributeSet attribs = null;
                if (baseDocument instanceof HTMLDocument) {
                    Element element = ((HTMLDocument) baseDocument).getCharacterElement(searchPlace);
                    attribs = element.getAttributes();
                }
                baseDocument.remove(searchPlace, findTerm.length());
                baseDocument.insertString(searchPlace, replaceTerm, attribs);
                jtpFindSource.setCaretPosition(searchPlace + replaceTerm.length());
                jtpFindSource.requestFocus();
                jtpFindSource.select(searchPlace, searchPlace + replaceTerm.length());
            } else {
                jtpFindSource.setCaretPosition(searchPlace + findTerm.length());
                jtpFindSource.requestFocus();
                jtpFindSource.select(searchPlace, searchPlace + findTerm.length());
            }
        }
    } catch (BadLocationException ble) {
        logException("BadLocationException in actionPerformed method", ble);
        new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                Translatrix.getTranslationString("ErrorBadLocationException"), SimpleInfoDialog.ERROR);
    }
    return searchPlace;
}

From source file:org.apache.jmeter.testbeans.gui.ComboStringEditor.java

private void startEditing() {
    JTextComponent textField = (JTextComponent) combo.getEditor().getEditorComponent();

    combo.setEditable(true);// w  ww  .  ja  v a2  s  . c  o m

    textField.requestFocusInWindow();
    String text = translate(initialEditValue);
    if (text == null) {
        text = ""; // will revert to last valid value if invalid
    }

    combo.setSelectedItem(text);

    int i = text.indexOf("${}");
    if (i != -1) {
        textField.setCaretPosition(i + 2);
    } else {
        textField.selectAll();
    }
}

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

public static void selectNone(JTextComponent textComponent) {
    textComponent.setCaretPosition(0);
}

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  ww .  jav 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);
    }

}

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 w  w . j  av a  2 s .  c o m

        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;// w w  w.j  a va  2  s.com
    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);
    }

}