List of usage examples for javax.swing.text JTextComponent getCaretPosition
@Transient public int getCaretPosition()
From source file:DragColorTextFieldDemo.java
public boolean importData(JComponent c, Transferable t) { JTextComponent tc = (JTextComponent) c; if (!canImport(c, t.getTransferDataFlavors())) { return false; }//from www .ja va 2 s.c om 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.autocompleter.AutoCompleteListener.java
private boolean atEndOfWord(JTextComponent textField) { int nextCharPosition = textField.getCaretPosition(); // position not at the end of input if (nextCharPosition < textField.getText().length()) { char nextChar = textField.getText().charAt(nextCharPosition); if (!Character.isWhitespace(nextChar)) { return false; }/*from www . ja va2 s . c om*/ } return true; }
From source file:net.sf.jabref.gui.AutoCompleteListener.java
protected int findNamePositionStatus(JTextComponent comp) { String upToCaret;//from w ww. j a va 2 s.com try { upToCaret = comp.getText(0, comp.getCaretPosition()); // Clip off evertyhing up to and including the last " and " before: upToCaret = upToCaret.substring(upToCaret.lastIndexOf(" and ") + 1); int commaIndex = upToCaret.indexOf(','); if (commaIndex < 0) { return AutoCompleteListener.ANY_NAME; } else { return AutoCompleteListener.FIRST_NAME; } } catch (BadLocationException ex) { return AutoCompleteListener.ANY_NAME; } }
From source file:net.sf.jabref.gui.autocompleter.AutoCompleteListener.java
private StringBuffer getCurrentWord(JTextComponent comp) { StringBuffer res = new StringBuffer(); String upToCaret;//from w w w . ja v a 2 s . c o m try { upToCaret = comp.getText(0, comp.getCaretPosition()); // We now have the text from the start of the field up to the caret position. // In most fields, we are only interested in the currently edited word, so we // seek from the caret backward to the closest space: if (!completer.isSingleUnitField()) { if ((comp.getCaretPosition() < comp.getText().length()) && Character.isWhitespace(comp.getText().charAt(comp.getCaretPosition()))) { // caret is in the middle of the text AND current character is a whitespace // that means: a new word is started and there is no current word return new StringBuffer(); } int piv = upToCaret.length() - 1; while ((piv >= 0) && !Character.isWhitespace(upToCaret.charAt(piv))) { piv--; } // piv points to whitespace char or piv is -1 // copy everything from the next char up to the end of "upToCaret" res.append(upToCaret.substring(piv + 1)); } else { // For fields such as "journal" it is more reasonable to try to complete on the entire // text field content, so we skip the searching and keep the entire part up to the caret: res.append(upToCaret); } LOGGER.debug("AutoCompListener: " + res); } catch (BadLocationException ignore) { // Ignored } return res; }
From source file:net.sf.jabref.gui.AutoCompleteListener.java
private StringBuffer getCurrentWord(JTextComponent comp) { StringBuffer res = new StringBuffer(); String upToCaret;//from w w w. j a va 2s .c om try { upToCaret = comp.getText(0, comp.getCaretPosition()); // We now have the text from the start of the field up to the caret position. // In most fields, we are only interested in the currently edited word, so we // seek from the caret backward to the closest space: if (!completer.isSingleUnitField()) { if ((comp.getCaretPosition() < comp.getText().length()) && Character.isWhitespace(comp.getText().charAt(comp.getCaretPosition()))) { // caret is in the middle of the text AND current character is a whitespace // that means: a new word is started and there is no current word return null; } int piv = upToCaret.length() - 1; while ((piv >= 0) && !Character.isWhitespace(upToCaret.charAt(piv))) { piv--; } // priv points to whitespace char or priv is -1 // copy everything from the next char up to the end of "upToCaret" res.append(upToCaret.substring(piv + 1)); } else { // For fields such as "journal" it is more reasonable to try to complete on the entire // text field content, so we skip the searching and keep the entire part up to the caret: res.append(upToCaret); } //Util.pr("AutoCompListener: "+res.toString()); } catch (BadLocationException ignore) { } return res; }
From source file:com.mindcognition.mindraider.ui.swing.concept.annotation.renderer.AbstractTextAnnotationRenderer.java
/** * Search annotation from the current carret position. *//*from ww w. jav 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:ch.zhaw.iamp.rct.ui.GrammarWindow.java
private void insertTabAsSpace(KeyEvent event, JTextComponent component) { try {/*from w w w.ja v a 2 s . c om*/ int caretPostion = component.getCaretPosition() - 1; component.getDocument().remove(caretPostion, 1); component.getDocument().insertString(caretPostion, " ", null); event.consume(); } catch (BadLocationException ex) { System.out.println("Could not insert a tab: " + ex.getMessage()); } }
From source file:ch.zhaw.iamp.rct.ui.GrammarWindow.java
private void removeTabIfPossilbe(KeyEvent event, JTextComponent component) { try {/* w w w . ja v a 2 s .co m*/ Document doc = component.getDocument(); int caretPostion = component.getCaretPosition(); int lineStartIndex = doc.getText(0, caretPostion).lastIndexOf('\n') + 1; lineStartIndex = lineStartIndex < 0 ? 0 : lineStartIndex; lineStartIndex = lineStartIndex >= doc.getLength() ? doc.getLength() - 1 : lineStartIndex; int scanEndIndex = lineStartIndex + 4 <= doc.getLength() ? lineStartIndex + 4 : doc.getLength(); for (int i = 0; i < 4 && i + lineStartIndex < scanEndIndex; i++) { if (doc.getText(lineStartIndex, 1).matches(" ")) { doc.remove(lineStartIndex, 1); } else if (doc.getText(lineStartIndex, 1).matches("\t")) { doc.remove(lineStartIndex, 1); break; } else { break; } } event.consume(); } catch (BadLocationException ex) { System.out.println("Could not insert a tab: " + ex.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;//from w ww. j av a 2s.co 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;/*from w w w .j a v a 2 s . com*/ } 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(); }