Java Code Examples for javax.swing.text.Caret

The following examples show how to use javax.swing.text.Caret. These examples are extracted from open source projects. 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 Project: netbeans   Source File: PHPActionTestBase.java    License: Apache License 2.0 6 votes vote down vote up
protected void testInFile(String file, String actionName) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos+1);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();

    runKitAction(ta, actionName, null);

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, goldenFileExtension());
}
 
Example 2
Source Project: netbeans   Source File: CslEditorKit.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void afterBreak(JTextComponent target, BaseDocument doc, Caret caret,
    Object cookie) {
    if (completionSettingEnabled()) {
        if (cookie != null) {
            if (cookie instanceof Integer) {
                // integer
                int dotPos = ((Integer)cookie).intValue();
                if (dotPos != -1) {
                    caret.setDot(dotPos);
                } else {
                    int nowDotPos = caret.getDot();
                    caret.setDot(nowDotPos + 1);
                }
            }
        }
    }
}
 
Example 3
Source Project: netbeans   Source File: ActionFactory.java    License: Apache License 2.0 6 votes vote down vote up
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        try {
            int pos = Utilities.getRowFirstNonWhite((BaseDocument)target.getDocument(),
                                                    caret.getDot());
            if (pos >= 0) {
                boolean select = BaseKit.selectionFirstNonWhiteAction.equals(getValue(Action.NAME));
                if (select) {
                    caret.moveDot(pos);
                } else {
                    caret.setDot(pos);
                }
            }
        } catch (BadLocationException e) {
            target.getToolkit().beep();
        }
    }
}
 
Example 4
Source Project: netbeans   Source File: HtmlPaletteUtilities.java    License: Apache License 2.0 6 votes vote down vote up
private static int insert(String s, JTextComponent target, Document doc) 
throws BadLocationException 
{

    int start = -1;
    try {
        //at first, find selected text range
        Caret caret = target.getCaret();
        int p0 = Math.min(caret.getDot(), caret.getMark());
        int p1 = Math.max(caret.getDot(), caret.getMark());
        doc.remove(p0, p1 - p0);
        
        //replace selected text by the inserted one
        start = caret.getDot();
        doc.insertString(start, s, null);
    }
    catch (BadLocationException ble) {}
    
    return start;
}
 
Example 5
Source Project: netbeans   Source File: EntityClass.java    License: Apache License 2.0 6 votes vote down vote up
public boolean handleTransfer(JTextComponent targetComponent) {
    try {
        jsfLibrariesSupport = PaletteUtils.getJsfLibrariesSupport(targetComponent);
        if (jsfLibrariesSupport == null) {
            return false;
        }
        Caret caret = targetComponent.getCaret();
        int position0 = Math.min(caret.getDot(), caret.getMark());
        int position1 = Math.max(caret.getDot(), caret.getMark());
        int len = targetComponent.getDocument().getLength() - position1;
        boolean containsFView = targetComponent.getText(0, position0).contains("<f:view>")
                && targetComponent.getText(position1, len).contains("</f:view>");
        String body = createBody(targetComponent, !containsFView);
        JSFPaletteUtilities.insert(body, targetComponent);
        jsfLibrariesSupport.importLibraries(DefaultLibraryInfo.HTML, DefaultLibraryInfo.JSF_CORE);
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
        return false;
    } catch (BadLocationException ble) {
        Exceptions.printStackTrace(ble);
        return false;
    }

    return true;
}
 
Example 6
Source Project: netbeans   Source File: TransposeLettersAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (target != null) {
        final Document doc = target.getDocument();
        DocUtils.runAtomicAsUser(doc, new Runnable() {
            @Override
            public void run() {
                Caret caret = target.getCaret();
                if(caret instanceof EditorCaret) {
                    EditorCaret editorCaret = (EditorCaret) caret;
                    for (CaretInfo caretInfo : editorCaret.getSortedCarets()) {
                        if (!DocUtils.transposeLetters(doc, caretInfo.getDot())) {
                            // Cannot transpose (at end of doc) => beep
                            target.getToolkit().beep();
                        }
                    }
                } else {
                    if (!DocUtils.transposeLetters(doc, target.getCaretPosition())) {
                        // Cannot transpose (at end of doc) => beep
                        target.getToolkit().beep();
                    }
                }
            }
        });
    }
}
 
Example 7
Source Project: netbeans   Source File: JSFPaletteUtilities.java    License: Apache License 2.0 6 votes vote down vote up
private static int insert(String s, JTextComponent target, Document doc) throws BadLocationException {
    int start = -1;
    try {
        //at first, find selected text range
        Caret caret = target.getCaret();
        int p0 = Math.min(caret.getDot(), caret.getMark());
        int p1 = Math.max(caret.getDot(), caret.getMark());
        doc.remove(p0, p1 - p0);

        //replace selected text by the inserted one
        start = caret.getDot();
        doc.insertString(start, s, null);
    } catch (BadLocationException ble) {
    }

    return start;
}
 
Example 8
Source Project: netbeans   Source File: BracesMatchHighlighting.java    License: Apache License 2.0 6 votes vote down vote up
private void refresh() {
    if (released) {
        return; // No longer notify the matcher since it would leak to memory leak of MasterMatcher.lastResult
    }

    Caret c = this.caret;
    if (c == null) {
        bag.clear();
    } else {
        MasterMatcher.get(component).highlight(
            document,
            c.getDot(), 
            bag, 
            bracesMatchColoring, 
            bracesMismatchColoring,
            bracesMatchMulticharColoring,
            bracesMismatchMulticharColoring
        );
    }
}
 
Example 9
Source Project: netbeans   Source File: I18nManager.java    License: Apache License 2.0 6 votes vote down vote up
/** Highlights found hasrdcoded string. */
private void highlightHCString() {
    HardCodedString hStr = hcString;
    
    if (hStr == null) {
        return;
    }
    
    // Highlight found hard coded string.
    Caret caret = caretWRef.get();
    
    if (caret != null) {
        caret.setDot(hStr.getStartPosition().getOffset());
        caret.moveDot(hStr.getEndPosition().getOffset());
    }
}
 
Example 10
Source Project: netbeans   Source File: ExtKit.java    License: Apache License 2.0 6 votes vote down vote up
public @Override void actionPerformed(ActionEvent evt, JTextComponent target) {
    String cmd = evt.getActionCommand();
    int mod = evt.getModifiers();

    // Dirty fix for Completion shortcut on Unix !!!
    if (cmd != null && cmd.equals(" ") && (mod == ActionEvent.CTRL_MASK)) { // NOI18N
        // Ctrl + SPACE
    } else {
        Caret caret = target.getCaret();
        if (caret instanceof ExtCaret) {
            ((ExtCaret)caret).requestMatchBraceUpdateSync(); // synced bracket update
        }
        super.actionPerformed(evt, target);
    }

    if ((target != null) && (evt != null)) {
        if ((cmd != null) && (cmd.length() == 1)) {
            // Check whether char that should reindent the line was inserted
            checkIndentHotChars(target, cmd);

            // Check the completion
            checkCompletion(target, cmd);
        }
    }
}
 
Example 11
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
@Override public void actionPerformed(ActionEvent e) {
  JTextComponent target = getTextComponent(e);
  if (Objects.nonNull(target) && target.isEditable()) {
    Caret caret = target.getCaret();
    int dot = caret.getDot();
    int mark = caret.getMark();
    if (DefaultEditorKit.deletePrevCharAction.equals(getValue(Action.NAME))) {
      // @see javax/swing/text/DefaultEditorKit.java DeletePrevCharAction
      if (dot == 0 && mark == 0) {
        return;
      }
    } else {
      // @see javax/swing/text/DefaultEditorKit.java DeleteNextCharAction
      Document doc = target.getDocument();
      if (dot == mark && doc.getLength() == dot) {
        return;
      }
    }
  }
  deleteAction.actionPerformed(e);
}
 
Example 12
Source Project: netbeans   Source File: MulticaretHandler.java    License: Apache License 2.0 6 votes vote down vote up
private MulticaretHandler(final JTextComponent c) {
    this.doc = c.getDocument();
    doc.render(() -> {
        Caret caret = c.getCaret();
        if (caret instanceof EditorCaret) {
            List<CaretInfo> carets = ((EditorCaret) caret).getCarets();
            if (carets.size() > 1) {
                this.regions = new ArrayList<>(carets.size());
                carets.forEach((ci) -> {
                    try {
                        int[] block = ci.isSelectionShowing() ? null : Utilities.getIdentifierBlock(c, ci.getDot());
                        Position start = NbDocument.createPosition(doc, block != null ? block[0] : ci.getSelectionStart(), Position.Bias.Backward);
                        Position end = NbDocument.createPosition(doc, block != null ? block[1] : ci.getSelectionEnd(), Position.Bias.Forward);
                        regions.add(new MutablePositionRegion(start, end));
                    } catch (BadLocationException ex) {}
                });
                Collections.reverse(regions);
            }
        }
    });
}
 
Example 13
Source Project: seaglass   Source File: MacEditorKit.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * The operation to perform when this action is triggered.
 *
 * @param e DOCUMENT ME!
 */
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);

    if (target != null) {

        // target.getUI().getNextVisualPositionFrom(t
        Caret caret = target.getCaret();
        int   dot   = caret.getDot();

        verticalAction.actionPerformed(e);

        if (dot == caret.getDot()) {
            Point magic = caret.getMagicCaretPosition();

            beginEndAction.actionPerformed(e);
            caret.setMagicCaretPosition(magic);
        }
    }
}
 
Example 14
Source Project: netbeans   Source File: XMLKit.java    License: Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target == null) return;
    if (!target.isEditable() || !target.isEnabled()) {
        problem(null);
        return;
    }
    Caret caret = target.getCaret();
    BaseDocument doc = (BaseDocument)target.getDocument();
    try {
        doc.dump(System.out);    
        if (target == null)  throw new BadLocationException(null,0);  // folish compiler
    } catch (BadLocationException e) {
        problem(null);
    }
}
 
Example 15
Source Project: darklaf   Source File: ToggleInsertAction.java    License: MIT License 5 votes vote down vote up
@Override
public void actionPerformed(final ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null) {
        Caret c = target.getCaret();
        if (c instanceof DarkCaret) {
            ((DarkCaret) c).setInsertMode(!((DarkCaret) c).isInsertMode());
        }
    }
}
 
Example 16
Source Project: netbeans   Source File: InsertTabAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(final ActionEvent evt, final JTextComponent target) {
    BaseKit.InsertTabAction insertTabAction = new BaseKit.InsertTabAction();
    insertTabAction.actionPerformed(evt, target);
    if (target != null) {
        if (!target.isEditable() || !target.isEnabled()) {
            target.getToolkit().beep();
            return;
        }
        final Caret caret = target.getCaret();
        final BaseDocument doc = (BaseDocument) target.getDocument();
        doc.runAtomic(new TabReplacer(doc, caret.getDot()));
    }
}
 
Example 17
Source Project: trygve   Source File: RTDebuggerWindow.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override public int getSelectionStart() {
 final Caret caret = super.getCaret();
 if (null == caret) {
  setCaret(new DefaultCaret());
 }
 final int start = null == caret? 0: Math.min(caret.getDot(), caret.getMark());
 return start;
}
 
Example 18
Source Project: ghidra   Source File: TextFieldLinker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void keyPressed(KeyEvent e) {
	Caret caret = linked.field.getCaret();
	boolean sel = caret.getMark() != caret.getDot();
	switch (e.getKeyCode()) {
		case KeyEvent.VK_BACK_SPACE:
			if (!sel && state.isAfterSep(linked.index)) {
				state.removeSep(linked.index - 1);
				e.consume();
			}
			break;
		case KeyEvent.VK_CLEAR:
			clear();
			break;
		case KeyEvent.VK_DELETE:
			if (!sel && state.isBeforeSep(linked.index)) {
				state.removeSep(linked.index);
				e.consume();
			}
			break;
		case KeyEvent.VK_KP_LEFT:
		case KeyEvent.VK_LEFT:
			if (state.isAfterSep(linked.index)) {
				state.navigateFieldLeft(linked.index - 1);
			}
			break;
		case KeyEvent.VK_KP_RIGHT:
		case KeyEvent.VK_RIGHT:
			if (state.isBeforeSep(linked.index)) {
				state.navigateFieldRight(linked.index + 1);
			}
			break;
		default:
			return;
	}
	syncStateLater();
}
 
Example 19
Source Project: ghidra   Source File: TextFieldAutocompleter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A convenience function that returns the bottom on-screen position of the given field's
 * caret.
 * 
 * @param field the field, typically the one having focus
 * @return the on-screen position of the caret's bottom.
 */
protected Point getCaretPositionOnScreen(JTextField field) {
	FontMetrics metrics = field.getFontMetrics(field.getFont());
	Caret c = field.getCaret();
	Point p = c.getMagicCaretPosition(); // returns a shared reference
	if (p == null) {
		p = new Point(0, field.getBaseline(1, 1));
	}
	else {
		p = new Point(p);
	}
	p.y += metrics.getHeight();
	SwingUtilities.convertPointToScreen(p, field);
	return p;
}
 
Example 20
Source Project: netbeans   Source File: PhpCommentGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void insertNewline(String source, String reformatted, IndentPrefs preferences) throws Exception {
    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    source = source.substring(0, sourcePos) + source.substring(sourcePos + 1);
    Formatter formatter = getFormatter(null);

    int reformattedPos = reformatted.indexOf('^');
    assertNotNull(reformattedPos);
    reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos + 1);

    JEditorPane ta = getPane(source);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();
    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, preferences);

    runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n");

    // wait for generating comment
    Future<?> future = PhpCommentGenerator.RP.submit(new Runnable() {
        @Override
        public void run() {
        }
    });
    future.get();

    String formatted = doc.getText(0, doc.getLength());
    assertEquals(reformatted, formatted);

    if (reformattedPos != -1) {
        assertEquals(reformattedPos, caret.getDot());
    }
}
 
Example 21
Source Project: netbeans   Source File: CamelCaseActions.java    License: Apache License 2.0 5 votes vote down vote up
protected void moveToNewOffset(JTextComponent target, int offset, int length) throws BadLocationException {
    Caret caret = target.getCaret();
    if (caret instanceof BaseCaret && RectangularSelectionUtils.isRectangularSelection(target)) {
        ((BaseCaret) caret).extendRectangularSelection(true, true);
    } else {
        target.getCaret().moveDot(offset + length);
    }
}
 
Example 22
Source Project: netbeans   Source File: CslTestBase.java    License: Apache License 2.0 5 votes vote down vote up
protected void assertAutoQuery(QueryType queryType, String source, String typedText) {
    CodeCompletionHandler completer = getCodeCompleter();
    int caretPos = source.indexOf('^');
    source = source.substring(0, caretPos) + source.substring(caretPos+1);

    BaseDocument doc = getDocument(source);
    JTextArea ta = new JTextArea(doc);
    Caret caret = ta.getCaret();
    caret.setDot(caretPos);

    QueryType qt = completer.getAutoQuery(ta, typedText);
    assertEquals(queryType, qt);
}
 
Example 23
Source Project: netbeans   Source File: BraceCompletionDeleteAction.java    License: Apache License 2.0 5 votes vote down vote up
protected void charBackspaced (
    BaseDocument        document, 
    int                 offset, 
    Caret               caret, 
    char                character
) throws BadLocationException {
    TokenSequence tokenSequence = Utils.getTokenSequence (document, offset);
    if (tokenSequence != null) {
        String mimeType = tokenSequence.language ().mimeType ();
        try {
            Language l = LanguagesManager.getDefault ().getLanguage (mimeType);
            List<Feature> completes = l.getFeatureList ().getFeatures ("COMPLETE");
            Iterator<Feature> it = completes.iterator ();
            while (it.hasNext ()) {
                Feature complete = it.next ();
                if (complete.getType () != Feature.Type.STRING)
                    continue;
                String s = (String) complete.getValue ();
                int i = s.indexOf (':');
                if (i != 1) continue;
                String ss = document.getText (
                    caret.getDot (), 
                    s.length () - i - 1
                );
                if (s.endsWith (ss) && 
                    s.charAt (0) == character
                ) {
                    document.remove (caret.getDot (), s.length () - i - 1);
                    return;
                }
            }
        } catch (LanguageDefinitionNotFoundException ex) {
            // ignore the exception
        }
    }
    super.charBackspaced (document, offset, caret, character);
}
 
Example 24
Source Project: jdk8u-jdk   Source File: Test6462562.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean test(int pos, int selectionLength, String todo, Object expectedResult) {
    Object v0 = getValue();

    Caret caret = getCaret();
    caret.setDot(pos);
    if (selectionLength > 0) {
        caret.moveDot(pos + selectionLength);
    }

    String desc = todo;
    if (todo == BACKSPACE) {
        backspace.actionPerformed(dummyEvent);
    } else if (todo == DELETE) {
        delete.actionPerformed(dummyEvent);
    } else {
        desc = "insert('" + todo + "')";
        insert.actionPerformed(new ActionEvent(this, 0, todo));
    }

    try {
        commitEdit();
    } catch (ParseException e) {
        e.printStackTrace();
        failed = true;
        return false;
    }

    Object v1 = getValue();
    if (! v1.equals(expectedResult)) {
        System.err.printf("Failure: value='%s', mark=%d, dot=%d, action=%s\n",
                v0, pos, pos + selectionLength, desc);
        System.err.printf("   Result: '%s', expected: '%s'\n", v1, expectedResult);
        failed = true;
        return false;
    }
    return true;
}
 
Example 25
Source Project: netbeans   Source File: GroovyTypedTextInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private void reindent(BaseDocument doc, int offset, TokenId id, Caret caret)
    throws BadLocationException {
    TokenSequence<GroovyTokenId> ts = LexUtilities.getGroovyTokenSequence(doc, offset);

    if (ts != null) {
        ts.move(offset);

        if (!ts.moveNext() && !ts.movePrevious()) {
            return;
        }

        Token<GroovyTokenId> token = ts.token();

        if ((token.id() == id)) {
            final int rowFirstNonWhite = Utilities.getRowFirstNonWhite(doc, offset);
            // Ensure that this token is at the beginning of the line
            if (ts.offset() > rowFirstNonWhite) {
                return;
            }

            OffsetRange begin = OffsetRange.NONE;

            if (id == GroovyTokenId.RBRACE) {
                begin = LexUtilities.findBwd(doc, ts, GroovyTokenId.LBRACE, GroovyTokenId.RBRACE);
            } else if (id == GroovyTokenId.RBRACKET) {
                begin = LexUtilities.findBwd(doc, ts, GroovyTokenId.LBRACKET, GroovyTokenId.RBRACKET);
            }

            if (begin != OffsetRange.NONE) {
                int beginOffset = begin.getStart();
                int indent = GsfUtilities.getLineIndent(doc, beginOffset);
                previousAdjustmentIndent = GsfUtilities.getLineIndent(doc, offset);
                GsfUtilities.setLineIndentation(doc, offset, indent);
                previousAdjustmentOffset = caret.getDot();
            }
        }
    }
}
 
Example 26
Source Project: openjdk-jdk8u   Source File: Test6462562.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean test(int pos, int selectionLength, String todo, Object expectedResult) {
    Object v0 = getValue();

    Caret caret = getCaret();
    caret.setDot(pos);
    if (selectionLength > 0) {
        caret.moveDot(pos + selectionLength);
    }

    String desc = todo;
    if (todo == BACKSPACE) {
        backspace.actionPerformed(dummyEvent);
    } else if (todo == DELETE) {
        delete.actionPerformed(dummyEvent);
    } else {
        desc = "insert('" + todo + "')";
        insert.actionPerformed(new ActionEvent(this, 0, todo));
    }

    try {
        commitEdit();
    } catch (ParseException e) {
        e.printStackTrace();
        failed = true;
        return false;
    }

    Object v1 = getValue();
    if (! v1.equals(expectedResult)) {
        System.err.printf("Failure: value='%s', mark=%d, dot=%d, action=%s\n",
                v0, pos, pos + selectionLength, desc);
        System.err.printf("   Result: '%s', expected: '%s'\n", v1, expectedResult);
        failed = true;
        return false;
    }
    return true;
}
 
Example 27
Source Project: jdk8u_jdk   Source File: Test6462562.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean test(int pos, int selectionLength, String todo, Object expectedResult) {
    Object v0 = getValue();

    Caret caret = getCaret();
    caret.setDot(pos);
    if (selectionLength > 0) {
        caret.moveDot(pos + selectionLength);
    }

    String desc = todo;
    if (todo == BACKSPACE) {
        backspace.actionPerformed(dummyEvent);
    } else if (todo == DELETE) {
        delete.actionPerformed(dummyEvent);
    } else {
        desc = "insert('" + todo + "')";
        insert.actionPerformed(new ActionEvent(this, 0, todo));
    }

    try {
        commitEdit();
    } catch (ParseException e) {
        e.printStackTrace();
        failed = true;
        return false;
    }

    Object v1 = getValue();
    if (! v1.equals(expectedResult)) {
        System.err.printf("Failure: value='%s', mark=%d, dot=%d, action=%s\n",
                v0, pos, pos + selectionLength, desc);
        System.err.printf("   Result: '%s', expected: '%s'\n", v1, expectedResult);
        failed = true;
        return false;
    }
    return true;
}
 
Example 28
Source Project: netbeans   Source File: BracesMatchAction.java    License: Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e, JTextComponent component) {
    Document document = component.getDocument();
    Caret caret = component.getCaret();
    
    MasterMatcher.get(component).navigate(
        document,
        caret.getDot(), 
        caret,
        select
    );
}
 
Example 29
Source Project: netbeans   Source File: CommentsPanel.java    License: Apache License 2.0 5 votes vote down vote up
private void setupTextPane(final JTextPane textPane, String comment) {
    if( UIUtils.isNimbus() ) {
        textPane.setUI( new BasicTextPaneUI() );
    }
    textPane.setText(comment);
    
    Caret caret = textPane.getCaret();
    if (caret instanceof DefaultCaret) {
        ((DefaultCaret)caret).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
    }

    // attachments
    if (!attachmentIds.isEmpty()) {
        AttachmentHyperlinkSupport.Attachement a = AttachmentHyperlinkSupport.findAttachment(comment, attachmentIds);
        if (a != null) {
            String attachmentId = a.id;
            if (attachmentId != null) {
                int index = attachmentIds.indexOf(attachmentId);
                if (index != -1) {
                    BugzillaIssue.Attachment attachment = attachments.get(index);
                    AttachmentLink attachmentLink = new AttachmentLink(attachment);
                    HyperlinkSupport.getInstance().registerLink(textPane, new int[] {a.idx1, a.idx2}, attachmentLink);
                } else {
                    Bugzilla.LOG.log(Level.WARNING, "couldn''t find attachment id in: {0}", comment); // NOI18N
                }
            }
        }
    }

    // pop-ups
    textPane.setComponentPopupMenu(commentsPopup);

    textPane.setBackground(blueBackground);

    textPane.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
    textPane.setEditable(false);
    textPane.getAccessibleContext().setAccessibleName(NbBundle.getMessage(CommentsPanel.class, "CommentsPanel.textPane.AccessibleContext.accessibleName")); // NOI18N
    textPane.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(CommentsPanel.class, "CommentsPanel.textPane.AccessibleContext.accessibleDescription")); // NOI18N
}
 
Example 30
Source Project: netbeans   Source File: InsertSemicolonAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (!target.isEditable() || !target.isEnabled()) {
        target.getToolkit().beep();
        return;
    }
    final BaseDocument doc = (BaseDocument) target.getDocument();
    final Indent indenter = Indent.get(doc);
    final class R implements Runnable {
        public @Override void run() {
            try {
                Caret caret = target.getCaret();
                int dotpos = caret.getDot();
                int eoloffset = Utilities.getRowEnd(target, dotpos);
                doc.insertString(eoloffset, "" + what, null); //NOI18N
                if (withNewline) {
                    //This is code from the editor module, but it is
                    //a pretty strange way to do this:
                    doc.insertString(dotpos, "-", null); //NOI18N
                    doc.remove(dotpos, 1);
                    int eolDot = Utilities.getRowEnd(target, caret.getDot());
                    int newDotPos = indenter.indentNewLine(eolDot);
                    caret.setDot(newDotPos);
                }
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    indenter.lock();
    try {
        doc.runAtomicAsUser(new R());
    } finally {
        indenter.unlock();
    }
}