javax.swing.text.BadLocationException Java Examples

The following examples show how to use javax.swing.text.BadLocationException. 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: BaseDocument.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Print into given container.
 *
 * @param container printing container into which the printing will be done.
 * @param usePrintColoringMap use printing coloring settings instead
 *  of the regular ones.
 * @param lineNumberEnabled if set to false the line numbers will not be printed.
 *  If set to true the visibility of line numbers depends on the settings
 *  for the line number visibility.
 * @param startOffset start offset of text to print
 * @param endOffset end offset of text to print
 */
public void print(PrintContainer container, boolean usePrintColoringMap, boolean lineNumberEnabled, int startOffset,
                  int endOffset) {
    readLock();
    try {
        EditorUI editorUI;
        EditorKit kit = getEditorKit();
        if (kit instanceof BaseKit) {
            editorUI = ((BaseKit) kit).createPrintEditorUI(this, usePrintColoringMap, lineNumberEnabled);
        } else {
            editorUI = new EditorUI(this, usePrintColoringMap, lineNumberEnabled);
        }

        DrawGraphics.PrintDG printDG = new DrawGraphics.PrintDG(container);
        DrawEngine.getDrawEngine().draw(printDG, editorUI, startOffset, endOffset, 0, 0, Integer.MAX_VALUE);
    } catch (BadLocationException e) {
        LOG.log(Level.WARNING, null, e);
    } finally {
        readUnlock();
    }
}
 
Example #2
Source File: JIntegerTextField.java    From LGoodDatePicker with MIT License 6 votes vote down vote up
@Override
public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
        throws BadLocationException {
    if (skipFiltersWhileTrue) {
        super.remove(fb, offset, length);
        return;
    }
    String oldText = fb.getDocument().getText(0, fb.getDocument().getLength());
    StringBuilder newTextBuilder = new StringBuilder(oldText);
    newTextBuilder.delete(offset, (offset + length));
    String newText = newTextBuilder.toString();
    if (newText.trim().isEmpty() || oldText.equals("-1")) {
        setFieldToDefaultValue();
    } else if (allowNegativeNumbers() && newText.trim().equals("-")) {
        setFieldToNegativeOne();
    } else if (isValidInteger(newText)) {
        super.remove(fb, offset, length);
    } else {
        Toolkit.getDefaultToolkit().beep();
    }
}
 
Example #3
Source File: HyperlinkImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public int[] getHyperlinkSpan(Document doc, int offset, HyperlinkType type) {
    if (!(doc instanceof BaseDocument)) {
        return null;
    }
    
    try {
        BaseDocument bdoc = (BaseDocument) doc;
        int start = Utilities.getRowStart(bdoc, offset);
        int end = Utilities.getRowEnd(bdoc, offset);

        for (int[] span : Parser.recognizeURLs(DocumentUtilities.getText(doc, start, end - start))) {
            if (span[0] + start <= offset && offset <= span[1] + start) {
                return new int[] {
                    span[0] + start,
                    span[1] + start
                };
            }
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return null;
}
 
Example #4
Source File: CodeCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void modifyLine(BaseDocument doc, String mimeType, int offset) throws BadLocationException {
    Feature feature = null;
    try {
        Language language = LanguagesManager.getDefault().getLanguage(mimeType);
        feature = language.getFeatureList ().getFeature (COMMENT_LINE);
    } catch (LanguageDefinitionNotFoundException e) {
    }
    if (feature != null) {
        String prefix = (String) feature.getValue("prefix"); // NOI18N
        if (prefix == null) {
            return;
        }
        String suffix = (String) feature.getValue("suffix"); // NOI18N
        if (suffix != null) {
            int end = Utilities.getRowEnd(doc, offset);
            doc.insertString(end, suffix, null);
        }
        doc.insertString(offset, prefix, null);
    }
}
 
Example #5
Source File: SetProperty.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleTransfer(JTextComponent targetComponent) {
    allBeans = initAllBeans(targetComponent);
    SetPropertyCustomizer c = new SetPropertyCustomizer(this, targetComponent);
    boolean accept = c.showDialog();
    if (accept) {
        String body = createBody();
        try {
            JspPaletteUtilities.insert(body, targetComponent);
        } catch (BadLocationException ble) {
            accept = false;
        }
    }

    return accept;
}
 
Example #6
Source File: WhereUsedQueryElement.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public String getDisplayText() {
    try {
        CharSequence text = parserResult.topLevelSnapshot.getText();
        OffsetRange orig = eLElement.getOriginalOffset();
        int astLineStart = GsfUtilities.getRowStart(text, orig.getStart());
        int astLineEnd = GsfUtilities.getRowEnd(text, orig.getEnd());
        OffsetRange nodeOffset = new OffsetRange(
                eLElement.getExpression().getOriginalOffset(targetNode.startOffset()), 
                eLElement.getExpression().getOriginalOffset(targetNode.endOffset())); 
        int expressionStart = orig.getStart() - astLineStart;
        int expressionEnd = expressionStart + (orig.getEnd() - orig.getStart());
        OffsetRange expressionOffset = new OffsetRange(expressionStart, expressionEnd);
        CharSequence line = text.subSequence(astLineStart, astLineEnd);
        return RefactoringUtil.encodeAndHighlight(line.toString(), expressionOffset, nodeOffset).trim();
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
        return eLElement.getExpression().getOriginalExpression(); //show the original expression in the text
    }
}
 
Example #7
Source File: AddDependencyPanel.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
/**
 * delayed change of query text
 */
@Override
public void stateChanged(ChangeEvent e) {
    Document doc = (Document) e.getSource();
    try {
        curTypedText = doc.getText(0, doc.getLength()).trim();
    } catch (BadLocationException ex) {
        // should never happen, nothing we can do probably
        return;
    }

    AddDependencyPanel.this.searchField.setForeground(defSearchC);

    if (curTypedText.length() > 0) {
        find(curTypedText);
    }
}
 
Example #8
Source File: GlyphGutter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private int getLineFromMouseEvent(MouseEvent e){
    int line = -1;
    EditorUI eui = editorUI;
    if (eui != null) {
        try{
            JTextComponent component = eui.getComponent();
            BaseDocument document = eui.getDocument();
            BaseTextUI textUI = (BaseTextUI)component.getUI();
            int clickOffset = textUI.viewToModel(component, new Point(0, e.getY()));
            line = Utilities.getLineOffset(document, clickOffset);
        }catch (BadLocationException ble) {
            LOG.log(Level.WARNING, null, ble);
        }
    }
    return line;
}
 
Example #9
Source File: SourceCodeDisplay.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private int charToLineNum(int charNum) {
    if (charNum == -1) {
        return -1;
    }
    try {
        for (int i = 1; true; i++) {
            if (frame.getSourceCodeTextPane().getLineOffset(i) > charNum) {
                return i - 1;
            } else if (frame.getSourceCodeTextPane().getLineOffset(i) == -1) {
                return -1;
            }
        }
    } catch (BadLocationException ble) {
        return -1;
    }
}
 
Example #10
Source File: OurSyntaxDocument.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Reapply styles assuming the given line has just been modified
 */
private final void do_update(int line) throws BadLocationException {
    String content = toString();
    int lineCount = do_getLineCount();
    while (line > 0 && (line >= comments.size() || comments.get(line) == Mode.NONE))
        line--; // "-1" in comments array are always contiguous
    Mode comment = do_reapply(line == 0 ? Mode.ALLOY : comments.get(line), content, line);
    for (line++; line < lineCount; line++) { // update each subsequent line
                                            // until it already starts
                                            // with its expected comment
                                            // mode
        if (line < comments.size() && comments.get(line) == comment)
            break;
        else
            comment = do_reapply(comment, content, line);
    }
}
 
Example #11
Source File: BaseDocument.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Removes portion of a document */
    public @Override void remove(int offset, int length) throws BadLocationException {
//        if (LOG_EDT.isLoggable(Level.FINE)) { // Only permit operations in EDT
//            if (!SwingUtilities.isEventDispatchThread()) {
//                throw new IllegalStateException("BaseDocument.insertString not in EDT: offset=" + // NOI18N
//                        offset + ", len=" + length); // NOI18N
//            }
//        }

        // Always acquire atomic lock (it simplifies processing and improves readability)
        atomicLockImpl();
        try {
            checkModifiable(offset);
            DocumentFilter filter = getDocumentFilter();
            if (filter != null) {
                filter.remove(getFilterBypass(), offset, length);
            } else {
                handleRemove(offset, length);
            }
        } finally {
            atomicUnlockImpl(true);
        }
    }
 
Example #12
Source File: GenerateJavadocAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void generate(final Document doc, final Descriptor desc, final JTextComponent jtc) throws BadLocationException {
    final Indent ie = Indent.get(doc);
    try {
        ie.lock();
        NbDocument.runAtomicAsUser((StyledDocument) doc, new Runnable() {

            public void run() {
                try {
                    int caretPos = jtc.getCaretPosition();
                    generateJavadoc(doc, desc, ie);
                    // move caret
                    jtc.setCaretPosition(caretPos);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }

        });
    } finally {
        ie.unlock();
    }
}
 
Example #13
Source File: DocPositionRegion.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public String getText () {
    final String[] result = new String[1];
    final Document doc = this.doc.get();
    if (doc != null) {
        doc.render(new Runnable() {
            public void run () {
                try {
                    result[0] = doc.getText(getStartOffset(), getLength());
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        });
    }
    return result[0];
}
 
Example #14
Source File: CheckAttributedTree.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/** Add a highlighted region based on the positions in an Info object. */
private void addHighlight(Highlighter h, Info info, Color c) {
    int start = info.start;
    int end = info.end;
    if (start == -1 && end == -1)
        return;
    if (start == -1)
        start = end;
    if (end == -1)
        end = start;
    try {
        h.addHighlight(info.start, info.end,
                new DefaultHighlighter.DefaultHighlightPainter(c));
        if (info.pos != -1) {
            Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
            h.addHighlight(info.pos, info.pos + 1,
                new DefaultHighlighter.DefaultHighlightPainter(c2));
        }
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * @param doc non-null document.
 * @param offset offset to translate to line and column info.
 * @param separator non-null separator of line and column info (either single charater or a string).s
 * @return non-null line and column info for the given offset.
 * @since 1.40
 */
public static String debugPosition(BaseDocument doc, int offset, String separator) {
    String ret;

    if (offset >= 0) {
        try {
            int line = getLineOffset(doc, offset) + 1;
            int col = getVisualColumn(doc, offset) + 1;
            ret = String.valueOf(line) + separator + String.valueOf(col); // NOI18N
        } catch (BadLocationException e) {
            ret = NbBundle.getBundle(BaseKit.class).getString( WRONG_POSITION_LOCALE )
                  + ' ' + offset + " > " + doc.getLength(); // NOI18N
        }
    } else {
        ret = String.valueOf(offset);
    }

    return ret;
}
 
Example #16
Source File: CompletionContext.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public CompletionContext(Document doc, int caretOffset) {
    this.doc = doc;
    this.caretOffset = caretOffset;

    try {
        this.support = XMLSyntaxSupport.getSyntaxSupport(doc);
    } catch (ClassCastException cce) {
        LOGGER.log(Level.FINE, cce.getMessage());
        this.support = XMLSyntaxSupport.createSyntaxSupport(doc);
    }
    this.documentContext = EditorContextFactory.getDocumentContext(doc, caretOffset);
    this.lastTypedChar = support.lastTypedChar();
    try {
        initContext();
    } catch (BadLocationException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #17
Source File: AnnotationView.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private synchronized int getModelToViewImpl(int line) throws BadLocationException {
    int docLines = Utilities.getRowCount(doc);
    
    if (modelToViewCache == null || height != pane.getHeight() || lines != docLines) {
        modelToViewCache = new int[Utilities.getRowCount(doc) + 2];
        lines = Utilities.getRowCount(doc);
        height = pane.getHeight();
    }
    
    if (line >= docLines)
        return -1;
    
    int result = modelToViewCache[line + 1];
    
    if (result == 0) {
        int lineOffset = Utilities.getRowStartFromLineOffset((BaseDocument) pane.getDocument(), line);
        
        modelToViewCache[line + 1] = result = getYFromPos(lineOffset);
    }
    
    if (result == (-1))
        result = 0;
    
    return result;
}
 
Example #18
Source File: SpringXMLConfigCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void substituteText(JTextComponent c, final int offset, final int len, String toAdd) {
    final BaseDocument doc = (BaseDocument) c.getDocument();
    CharSequence prefix = getSubstitutionText();
    String text = prefix.toString();
    if(toAdd != null) {
        text += toAdd;
    }
    final String finalText = text;
    doc.runAtomic(new Runnable() {

        @Override
        public void run() {
            try {
                Position position = doc.createPosition(offset);
                doc.remove(offset, len);
                doc.insertString(position.getOffset(), finalText.toString(), null);
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
}
 
Example #19
Source File: FoldHierarchyTransactionImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public FoldHierarchyTransactionImpl(FoldHierarchyExecution execution, boolean suppressEvents) {
    this.execution = execution;
    this.affectedStartOffset = -1;
    this.affectedEndOffset = -1;
    this.suppressEvents = suppressEvents;
    
    this.transaction = SpiPackageAccessor.get().createFoldHierarchyTransaction(this);
    this.dmgCounter = execution.getDamagedCount();
    if (dmgCounter > 0) {
        String t = null;
        JTextComponent comp = execution.getComponent();
        if (comp != null) {
            Document doc = comp.getDocument();
            try {
                t = doc.getText(0, doc.getLength());
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        if (debugFoldHierarchy) {
            initialSnapshot = execution.toString() + 
                              "\nContent at previous commit:\n====\n" + execution.getCommittedContent() + "\n====\n" +
                              "\nText content:\n====\n" + t + "\n====\n";
        }
    }
}
 
Example #20
Source File: PUCompletionProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static int getRowFirstNonWhite(StyledDocument doc, int offset)
        throws BadLocationException {
    Element lineElement = doc.getParagraphElement(offset);
    int start = lineElement.getStartOffset();
    while (start + 1 < lineElement.getEndOffset()) {
        try {
            if (doc.getText(start, 1).charAt(0) != ' ') {
                break;
            }
        } catch (BadLocationException ex) {
            throw (BadLocationException) new BadLocationException(
                    "calling getText(" + start + ", " + (start + 1)
                    + ") on doc of length: " + doc.getLength(), start).initCause(ex);
        }
        start++;
    }
    return start;
}
 
Example #21
Source File: SwingLogPanel.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Truncate the log to the given length; if the log is shorter than the number
 * given, then nothing happens.
 */
void setLength(int newLength) {
    if (log == null)
        return;
    clearError();
    StyledDocument doc = log.getStyledDocument();
    int n = doc.getLength();
    if (n <= newLength)
        return;
    try {
        doc.remove(newLength, n - newLength);
    } catch (BadLocationException e) {
        // Harmless
    }
    if (lastSize > doc.getLength()) {
        lastSize = doc.getLength();
    }
}
 
Example #22
Source File: OurSyntaxUndoableDocument.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called by Swing to delete text from this document.
 */
@Override
public void remove(int offset, int length) throws BadLocationException {
    if (length == 0)
        return;
    if (undone > 0) {
        now = now - undone;
        undone = 0;
    } // clear the REDO entries
    String string = toString().substring(offset, offset + length);
    super.remove(offset, length);
    if (now > 0 && !insert[now - 1]) { // merge with last edit if possible
        if (where[now - 1] == offset) {
            text[now - 1] += string;
            return;
        }
        if (where[now - 1] == offset + length) {
            where[now - 1] = offset;
            text[now - 1] = string + text[now - 1];
            return;
        }
    }
    if (now >= MAXUNDO) {
        arraycopy(insert, 1, insert, 0, MAXUNDO - 1);
        arraycopy(text, 1, text, 0, MAXUNDO - 1);
        arraycopy(where, 1, where, 0, MAXUNDO - 1);
        now--;
    }
    insert[now] = false;
    text[now] = string;
    where[now] = offset;
    now++;
}
 
Example #23
Source File: FoldContentReaders.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public CharSequence readContent(String mime, Document d, Fold f, FoldTemplate ft) throws BadLocationException {
    List<ContentReader> readers = getReaders(mime, f.getType());
    for (ContentReader r : readers) {
        CharSequence chs = r.read(d, f, ft);
        if (chs != null) {
            return chs;
        }
    }
    return null;
}
 
Example #24
Source File: Fold.java    From netbeans with Apache License 2.0 5 votes vote down vote up
void setStartOffset(Document doc, int startOffset)
throws BadLocationException {
    if (isRootFold()) {
        throw new IllegalStateException("Cannot set endOffset of root fold"); // NOI18N
    } else {
        this.startPos = doc.createPosition(startOffset);
    }
}
 
Example #25
Source File: AboutDialog.java    From Spade with GNU General Public License v3.0 5 votes vote down vote up
public static void append(StyledDocument doc, String str, String sty)
{
	try
	{
		doc.insertString(doc.getLength(), str, doc.getStyle(sty));
	}
	catch(BadLocationException e)
	{
		e.printStackTrace();
	}
}
 
Example #26
Source File: XMLSyntaxSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void insertUpdate(DocumentEvent e) {
    int start = e.getOffset();
    int len = e.getLength();
    try {
        String s = e.getDocument().getText(start + len - 1, 1);
        lastInsertedChar = s.charAt(0);
    } catch (BadLocationException e1) {
    }
}
 
Example #27
Source File: DocumentSizeFilter.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
    throws BadLocationException {
  if ((fb.getDocument().getLength() + str.length()) <= maxCharacters)
    super.insertString(fb, offs, str, a);
  else
    Toolkit.getDefaultToolkit().beep();
}
 
Example #28
Source File: MapcalcController.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
protected void insertTextToFunctionArea( String newText ) {
    // AttributeSet attrs=((StyledEditorKit)_functionArea.getEditorKit()).getInputAttributes();
    try {
        _functionArea.getDocument().insertString(_functionArea.getCaretPosition(), newText, null);
    } catch (BadLocationException e) {
        addTextToFunctionArea(newText);
    }
}
 
Example #29
Source File: LineDocumentUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Get the last non-white character on the line. The document.isWhitespace()
 * is used to test whether the particular character is white space or not.
 *
 * @param doc document to operate on
 * @param offset position in document anywhere on the line
 * @return position of the last non-white char on the line or -1 if there's
 * no non-white character on that line.
 */
public static int getLineLastNonWhitespace(@NonNull LineDocument doc, int offset)
throws BadLocationException
{
    checkOffsetValid(doc, offset);
    CharClassifier classifier = getValidClassifier(doc);
    CharSequence docText = DocumentUtilities.getText(doc);
    Element lineElement = doc.getParagraphElement(offset);
    return TextSearchUtils.getPreviousNonWhitespace(docText, classifier,
        lineElement.getEndOffset() - 1,
        lineElement.getStartOffset()
    );
}
 
Example #30
Source File: Test8030118.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        this.doc.remove(0, this.doc.getLength());
    } catch (BadLocationException exception) {
        throw new Error("unexpected", exception);
    }
    this.latch.countDown();
}