Java Code Examples for javax.swing.text.JTextComponent#select()

The following examples show how to use javax.swing.text.JTextComponent#select() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ActionUtils.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 * 
 * Note that the strings returned will not contain the terminating line feeds
 * 
 * The text component will then have the full lines set as selection
 * @param target
 * @return String[] of lines spanning selection / or Dot
 */
public static String[] getSelectedLines(JTextComponent target) {
    String[] lines = null;
    try {
        PlainDocument pDoc = (PlainDocument) target.getDocument();
        int start = pDoc.getParagraphElement(target.getSelectionStart()).getStartOffset();
        int end;
        if (target.getSelectionStart() == target.getSelectionEnd()) {
            end = pDoc.getParagraphElement(target.getSelectionEnd()).getEndOffset();
        } else {
            // if more than one line is selected, we need to subtract one from the end
            // so that we do not select the line with the caret and no selection in it
            end = pDoc.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
        }
        target.select(start, end);
        lines = pDoc.getText(start, end - start).split("\n");
        target.select(start, end);
    } catch (BadLocationException ex) {
        Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
        lines = EMPTY_STRING_ARRAY;
    }
    return lines;
}
 
Example 2
Source File: ActionUtils.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * If the selection is multi lined, then the full lines are selected,
 * otherwise, nothing is done.
 * @param target
 * @return true if the selection is multi-line, or a whole line
 */
public static boolean selectLines(JTextComponent target) {
	if (target.getSelectionStart() == target.getSelectionEnd()) {
		return false;
	}
	PlainDocument pDoc = (PlainDocument) target.getDocument();
	Element es = pDoc.getParagraphElement(target.getSelectionStart());
	// if more than one line is selected, we need to subtract one from the end
	// so that we do not select the line with the caret and no selection in it
	Element ee = pDoc.getParagraphElement(target.getSelectionEnd() - 1);
	if (es.equals(ee) && ee.getEndOffset() != target.getSelectionEnd()) {
		return false;
	}
	int start = es.getStartOffset();
	int end = ee.getEndOffset();
	target.select(start, end - 1);
	return true;
}
 
Example 3
Source File: SyntaxUtil.java    From nextreports-designer with Apache License 2.0 6 votes vote down vote up
/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 * 
 * Note that the strings returned will not contain the terminating line feeds.
 * 
 * The text component will then have the full lines set as selection.
 * 
 * @param target
 * @return String[] of lines spanning selection / or Dot
 */
public static String[] getSelectedLines(JTextComponent target) {
    String[] lines = null;
    try {
        PlainDocument document = (PlainDocument) target.getDocument();
        int start = document.getParagraphElement(target.getSelectionStart()).getStartOffset();
        int end;
        if (target.getSelectionStart() == target.getSelectionEnd()) {
            end = document.getParagraphElement(target.getSelectionEnd()).getEndOffset();
        } else {
            // if more than one line is selected, we need to subtract one from the end
            // so that we do not select the line with the caret and no selection in it
            end = document.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
        }
        target.select(start, end);
        lines = document.getText(start, end - start).split("\n");
        target.select(start, end);
    } catch (BadLocationException e) {
        LOG.error(e.getMessage(), e);
        lines = EMPTY_STRING_ARRAY;
    }
    
    return lines;
}
 
Example 4
Source File: IndentAction.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null) {
        String selected = target.getSelectedText();
        if (selected == null) {
            PlainDocument pDoc = (PlainDocument) target.getDocument();
            Integer tabStop = (Integer) pDoc.getProperty(PlainDocument.tabSizeAttribute);
            int lineStart = pDoc.getParagraphElement(target.getCaretPosition()).getStartOffset();
            int column = target.getCaretPosition() - lineStart;
            int needed = tabStop - (column % tabStop);
            target.replaceSelection(ActionUtils.SPACES.substring(0, needed));
        } else {
            String[] lines = ActionUtils.getSelectedLines(target);
            int start = target.getSelectionStart();
            StringBuilder sb = new StringBuilder();
            for (String line : lines) {
                sb.append('\t');
                sb.append(line);
                sb.append('\n');
            }
            target.replaceSelection(sb.toString());
            target.select(start, start + sb.length());
        }
    }
}
 
Example 5
Source File: UnindentAction.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    Integer tabStop = (Integer) target.getDocument().getProperty(PlainDocument.tabSizeAttribute);
    String indent = ActionUtils.SPACES.substring(0, tabStop);
    if (target != null) {
        String[] lines = ActionUtils.getSelectedLines(target);
        int start = target.getSelectionStart();
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (line.startsWith(indent)) {
                sb.append(line.substring(indent.length()));
            } else if (line.startsWith("\t")) {
                sb.append(line.substring(1));
            } else {
                sb.append(line);
            }
            sb.append('\n');
        }
        target.replaceSelection(sb.toString());
        target.select(start, start + sb.length());
    }
}
 
Example 6
Source File: ActionUtils.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Insert the given String into the textcomponent.  If the string contains
 * the | vertical BAr char, then it will not be inserted, and the cursor will
 * be set to its location.
 * If there are TWO vertical bars, then the text between them will be selected
 * <b>FIXME: add following feature
 * If the String is multi-line, then it will be indented with the same
 * indentattion as the line with pos.</b>
 * @param target
 * @param dot
 * @param toInsert
 * @throws javax.swing.text.BadLocationException
 */
public static void insertMagicString(JTextComponent target, int dot, String toInsert)
        throws BadLocationException {
    Document doc = target.getDocument();
    if (toInsert.indexOf('|') >= 0) {
        int ofst = toInsert.indexOf('|');
        int ofst2 = toInsert.indexOf('|', ofst + 1);
        toInsert = toInsert.replace("|", "");
        doc.insertString(dot, toInsert, null);
        dot = target.getCaretPosition();
        final int strLength = toInsert.length();
        if (ofst2 > 0) {
            // note that we already removed the first |, so end offset is now
            // one less than what it was.
            target.select(dot + ofst - strLength, dot + ofst2 - strLength - 1);
        } else {
            target.setCaretPosition(dot + ofst -strLength);
        }
    } else {
        doc.insertString(dot, toInsert, null);
    }
}
 
Example 7
Source File: ToggleCommentsAction.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * @param e 
 */
@Override
public void actionPerformed(JTextComponent target, SyntaxDocument sDoc,
        int dot, ActionEvent e) {
    if (lineCommentPattern == null) {
        lineCommentPattern = Pattern.compile("(^" + lineCommentStart + ")(.*)");
    }
    String[] lines = ActionUtils.getSelectedLines(target);
    int start = target.getSelectionStart();
    StringBuffer toggled = new StringBuffer();
    for (int i = 0; i < lines.length; i++) {
        Matcher m = lineCommentPattern.matcher(lines[i]);
        if (m.find()) {
            toggled.append(m.replaceFirst("$2"));
        } else {
            toggled.append(lineCommentStart);
            toggled.append(lines[i]);
        }
        toggled.append('\n');
    }
    target.replaceSelection(toggled.toString());
    target.select(start, start + toggled.length());
}
 
Example 8
Source File: ComboCompletionAction.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void actionPerformed(JTextComponent target, SyntaxDocument sdoc,
        int dot, ActionEvent e) {
    if (sdoc == null) {
        return;
    }
    Token token = sdoc.getTokenAt(dot);
    String abbrev = "";
    if (token != null) {
        abbrev = token.getString(sdoc);
        target.select(token.start, token.end());
    }
    if (dlg == null) {
        dlg = new ComboCompletionDialog(target);
    }
    dlg.displayFor(abbrev, items);
}
 
Example 9
Source File: VarDocSuggestion.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void implement() throws Exception {
    final BaseDocument doc = context.doc;
    final int caretOffset = getOffset(doc);
    final String commentText = getCommentText();
    final int indexOf = commentText.indexOf(getTypeTemplate());
    final EditList editList = getEditList(doc, caretOffset);
    final Position typeOffset = editList.createPosition(caretOffset + indexOf);
    editList.apply();
    if (typeOffset != null && typeOffset.getOffset() != -1) {
        JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
        if (target != null) {
            final int startOffset = typeOffset.getOffset();
            final int endOffset = startOffset + getTypeTemplate().length();
            if (indexOf != -1 && (endOffset <= doc.getLength())) {
                String s = doc.getText(startOffset, getTypeTemplate().length());
                if (getTypeTemplate().equals(s)) {
                    target.select(startOffset, endOffset);
                    scheduleShowingCompletion();
                }

            }
        }
    }
}
 
Example 10
Source File: CompleteWordAction.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void actionPerformed(JTextComponent target, SyntaxDocument sdoc,
        int dot, ActionEvent e) {
    Token current = sdoc.getWordAt(dot, wordsPattern);
    if (current == null) {
        return;
    }
    String cw = current.getString(sdoc);
    target.select(current.start, current.end());

    sdoc.readLock();
    List<String> matches = new ArrayList<String>();
    Matcher m = sdoc.getMatcher(wordsPattern, 0, current.start);
    addWords(m, cw, matches);
    m = sdoc.getMatcher(wordsPattern, current.end(), sdoc.getLength() - current.end());
    addWords(m, cw, matches);
    sdoc.readUnlock();
    if (matches.size() == 0) {
        return;
    }
    if (matches.size() == 1) {
        target.replaceSelection(matches.get(0));
        return;
    }
    if (dlg == null) {
        dlg = new ComboCompletionDialog(target);
    }
    dlg.displayFor(cw, matches);
}
 
Example 11
Source File: JTextObserver.java    From ccu-historian with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Deselects the text when a field loses the focus.
 * 
 * @param e  the event.
 */
public void focusLost(final FocusEvent e) {
    if (e.getSource() instanceof JTextComponent) {
        final JTextComponent tex = (JTextComponent) e.getSource();
        tex.select(0, 0);
    }
}
 
Example 12
Source File: Messages.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static String showInputDialog(Project project,
                                     @Nls String message,
                                     @Nls String title,
                                     @Nullable Icon icon,
                                     @Nullable String initialValue,
                                     @Nullable InputValidator validator,
                                     @Nullable TextRange selection) {
  if (isApplicationInUnitTestOrHeadless()) {
    return ourTestInputImplementation.show(message);
  }
  else {
    InputDialog dialog = new InputDialog(project, message, title, icon, initialValue, validator);

    final JTextComponent field = dialog.getTextField();
    if (selection != null) {
      // set custom selection
      field.select(selection.getStartOffset(), selection.getEndOffset());
    }
    else {
      // reset selection
      final int length = field.getDocument().getLength();
      field.select(length, length);
    }
    field.putClientProperty(DialogWrapperPeer.HAVE_INITIAL_SELECTION, true);

    dialog.show();
    return dialog.getInputString();
  }
}
 
Example 13
Source File: FindReplaceActions.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform a FindNext operation on the given text component.  Position
 * the caret at the start of the next found pattern
 * @param target
 */
public void doFindNext(JTextComponent target) {
    if (target == null || pattern == null) {
        return;
    }
    SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target);
    if (sDoc == null) {
        return;
    }
    int start = target.getCaretPosition() + 1;
    // we must advance the position by one, otherwise we will find
    // the same text again
    if (start >= sDoc.getLength()) {
        start = 0;
    }
    Matcher matcher = sDoc.getMatcher(pattern, start);
    if (matcher != null && matcher.find()) {
        // since we used an offset in the matcher, the matcher location
        // MUST be offset by that location
        target.select(matcher.start() + start, matcher.end() + start);
    } else {
        if (isWrap()) {
            matcher = sDoc.getMatcher(pattern);
            if (matcher != null && matcher.find()) {
                target.select(matcher.start(), matcher.end());
            } else {
                msgNotFound();
            }
        } else {
            msgNotFound();
        }
    }
}
 
Example 14
Source File: DocumentSearchData.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
/**
 * FInd the previous match
 * @param target
 * @return
 */
public boolean doFindPrev(JTextComponent target) {
	if (getPattern() == null) {
		return false;
	}
	SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target);
	if (sDoc == null) {
		return false;
	}
	int dot = target.getSelectionStart();
	Matcher matcher = sDoc.getMatcher(getPattern());
	if (matcher == null) {
		return false;
	}
	// we have no way of jumping to last match, so we need to
	// go throw all matches, and stop when we reach current pos
	int start = -1;
	int end = -1;
	while (matcher.find()) {
		if (matcher.end() >= dot) {
			break;
		}
		start = matcher.start();
		end = matcher.end();
	}
	if (end > 0) {
		target.select(start, end);
		return true;
	} else {
		return false;
	}
}
 
Example 15
Source File: ReflectCompletionAction.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void actionPerformed(JTextComponent target, SyntaxDocument sDoc,
        int dot, ActionEvent e) {
    Token t = sDoc.getTokenAt(dot);
    if(t != null) {
        target.select(t.start, t.end());
    }
    if (dlg == null) {
        dlg = new ReflectCompletionDialog(target);
    }
    dlg.displayFor(target);
}
 
Example 16
Source File: IdeaMessages.java    From react-native-console with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static String showInputDialog(@Nullable Project project, Component parentComponent, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator, @Nullable TextRange selection) {
    InputDialog dialog = new InputDialog(project, message, title, icon, initialValue, validator,
        new String[]{com.intellij.openapi.ui.Messages.OK_BUTTON}, 0);// Fix support with WebStorm 173(2017.3)
    JTextComponent field = dialog.getTextField();
    if (selection != null) {
      field.select(selection.getStartOffset(), selection.getEndOffset());
      field.putClientProperty(DialogWrapperPeer.HAVE_INITIAL_SELECTION, true);
    }

    dialog.show();
    return dialog.getInputString();
}
 
Example 17
Source File: NameAutocompleter.java    From plugins with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void keyTyped(KeyEvent e)
{
	if (!hiscoreConfig.autocomplete())
	{
		return;
	}

	final JTextComponent input = (JTextComponent) e.getSource();
	final String inputText = input.getText();

	// Only autocomplete if the selection end is at the end of the text.
	if (input.getSelectionEnd() != inputText.length())
	{
		return;
	}

	// Character to be inserted at the selection start.
	final String charToInsert = Character.toString(e.getKeyChar());

	// Don't attempt to autocomplete if the name is invalid.
	// This condition is also true when the user presses a key like backspace.
	if (INVALID_CHARS.matcher(charToInsert).find()
		|| INVALID_CHARS.matcher(inputText).find())
	{
		return;
	}

	// Check if we are already autocompleting.
	if (autocompleteName != null && autocompleteNamePattern.matcher(inputText).matches())
	{
		if (isExpectedNext(input, charToInsert))
		{
			try
			{
				// Insert the character and move the selection.
				final int insertIndex = input.getSelectionStart();
				Document doc = input.getDocument();
				doc.remove(insertIndex, 1);
				doc.insertString(insertIndex, charToInsert, null);
				input.select(insertIndex + 1, input.getSelectionEnd());
			}
			catch (BadLocationException ex)
			{
				log.warn("Could not insert character.", ex);
			}

			// Prevent default behavior.
			e.consume();
		}
		else // Character to insert does not match current autocompletion. Look for another name.
		{
			newAutocomplete(e);
		}
	}
	else // Search for a name to autocomplete
	{
		newAutocomplete(e);
	}
}
 
Example 18
Source File: InstantRenamePerformer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Creates a new instance of InstantRenamePerformer */
private InstantRenamePerformer(JTextComponent target, Set<Token> highlights, int caretOffset) throws BadLocationException {
    this.target = target;
    doc = target.getDocument();

    MutablePositionRegion mainRegion = null;
    List<MutablePositionRegion> regions = new ArrayList<MutablePositionRegion>();

    for (Token h : highlights) {
        // type parameter name is represented as ident -> ignore surrounding <> in rename
        int delta = h.id() == JavadocTokenId.IDENT && h.text().charAt(0) == '<' && h.text().charAt(h.length() - 1) == '>' ? 1 : 0;
        Position start = NbDocument.createPosition(doc, h.offset(null) + delta, Bias.Backward);
        Position end = NbDocument.createPosition(doc, h.offset(null) + h.length() - delta, Bias.Forward);
        MutablePositionRegion current = new MutablePositionRegion(start, end);
        
        if (isIn(current, caretOffset)) {
            mainRegion = current;
        } else {
            regions.add(current);
        }
    }

    if (mainRegion == null) {
        throw new IllegalArgumentException("No highlight contains the caret.");
    }

    regions.add(0, mainRegion);

    region = new SyncDocumentRegion(doc, regions);

    if (doc instanceof BaseDocument) {
        BaseDocument bdoc = ((BaseDocument) doc);
        bdoc.setPostModificationDocumentListener(this);

        UndoableEdit undo = new CancelInstantRenameUndoableEdit(this);
        for (UndoableEditListener l : bdoc.getUndoableEditListeners()) {
            l.undoableEditHappened(new UndoableEditEvent(doc, undo));
        }
    }

    target.addKeyListener(this);

    target.putClientProperty(InstantRenamePerformer.class, this);
    target.putClientProperty("NetBeansEditor.navigateBoundaries", mainRegion); // NOI18N
	
    requestRepaint();
    
    target.select(mainRegion.getStartOffset(), mainRegion.getEndOffset());
    
    span = region.getFirstRegionLength();
    
    registry.add(this);
    sendUndoableEdit(doc, CloneableEditorSupport.BEGIN_COMMIT_GROUP);
}
 
Example 19
Source File: InstantRefactoringPerformer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public InstantRefactoringPerformer(final JTextComponent target, int caretOffset, InstantRefactoringUI ui) {
    releaseAll();
    this.target = target;
    this.ui = ui;
    doc = target.getDocument();

    MutablePositionRegion mainRegion = null;
    List<MutablePositionRegion> regions = new ArrayList<>(ui.getRegions().size());

    for (MutablePositionRegion current : ui.getRegions()) {
        // TODO: type parameter name is represented as ident -> ignore surrounding <> in rename
        if (isIn(current, caretOffset)) {
            mainRegion = current;
        } else {
            regions.add(current);
        }
    }

    if (mainRegion == null) {
        throw new IllegalArgumentException("No highlight contains the caret.");
    }

    regions.add(0, mainRegion);

    region = new SyncDocumentRegion(doc, regions);

    if (doc instanceof BaseDocument) {
        BaseDocument bdoc = ((BaseDocument) doc);
        bdoc.addPostModificationDocumentListener(this);
        
        UndoableWrapper wrapper = MimeLookup.getLookup("text/x-java").lookup(UndoableWrapper.class);
        if(wrapper != null) {
            wrapper.setActive(true, this);
        }

        UndoableEdit undo = new CancelInstantRenameUndoableEdit(this);
        for (UndoableEditListener l : bdoc.getUndoableEditListeners()) {
            l.undoableEditHappened(new UndoableEditEvent(doc, undo));
        }
    }

    target.addKeyListener(this);

    target.putClientProperty(InstantRefactoringPerformer.class, this);
    target.putClientProperty("NetBeansEditor.navigateBoundaries", mainRegion); // NOI18N
	
    requestRepaint();
    
    target.select(mainRegion.getStartOffset(), mainRegion.getEndOffset());
    
    span = region.getFirstRegionLength();
    compl = new CompletionLayout(this);
    compl.setEditorComponent(target);
    final KeyStroke OKKS = ui.getKeyStroke();
    target.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(OKKS, OKActionKey);
    Action OKAction = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            if(registry.contains(InstantRefactoringPerformer.this)) {
                doFullRefactoring();
                target.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).remove(OKKS);
                target.getActionMap().remove(OKActionKey);
            } else {
                target.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).remove(OKKS);
                target.getActionMap().remove(OKActionKey);
            }
        }
    };
    target.getActionMap().put(OKActionKey, OKAction);
    final KeyStroke keyStroke = ui.getKeyStroke();
    compl.showCompletion(ui.getOptions(), caretOffset, Bundle.INFO_PressAgain(getKeyStrokeAsText(keyStroke)));
    
    registry.add(this);
}
 
Example 20
Source File: ActionUtils.java    From jpexs-decompiler with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Insert the given String into the textcomponent.  If the string contains
 * the | vertical BAr char, then it will not be inserted, and the cursor will
 * be set to its location.
 * If there are TWO vertical bars, then the text between them will be selected
 * If the toInsert String is multiLine, then indentation of all following lines
 * will be the same as the first line.  TAB characters will be replaced by
 * the number of spaces in the document's TAB property.
 * @param target
 * @param dot
 * @param toInsert
 * @throws javax.swing.text.BadLocationException
 */
public static void insertMagicString(JTextComponent target, int dot, String toInsert)
	throws BadLocationException {
	Document doc = target.getDocument();
	String[] lines = toInsert.split("\n");
	if (lines.length > 1) {
		// multi line strings will need to be indented
		String tabToSpaces = getTab(target);
		String currentLine = getLineAt(target, dot);
		String currentIndent = getIndent(currentLine);
		StringBuilder sb = new StringBuilder(toInsert.length());
		boolean firstLine = true;
		for (String l : lines) {
			if (!firstLine) {
				sb.append(currentIndent);
			}
			firstLine = false;
			// replace tabs with spaces.
			sb.append(l.replace("\t", tabToSpaces));
			sb.append("\n");
		}
		toInsert = sb.toString();
	}
	if (toInsert.indexOf('|') >= 0) {
		int ofst = toInsert.indexOf('|');
		int ofst2 = toInsert.indexOf('|', ofst + 1);
		toInsert = toInsert.replace("|", "");
		doc.insertString(dot, toInsert, null);
		dot = target.getCaretPosition();
		int strLength = toInsert.length();
		if (ofst2 > 0) {
			// note that we already removed the first |, so end offset is now
			// one less than what it was.
			target.select(dot + ofst - strLength, dot + ofst2 - strLength - 1);
		} else {
			target.setCaretPosition(dot + ofst - strLength);
		}
	} else {
		doc.insertString(dot, toInsert, null);
	}
}