Java Code Examples for javax.swing.text.BadLocationException

The following examples show how to use javax.swing.text.BadLocationException. 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: HyperlinkImpl.java    License: 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 2
Source Project: netbeans   Source File: FoldHierarchyTransactionImpl.java    License: 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 3
Source Project: LGoodDatePicker   Source File: JIntegerTextField.java    License: 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 4
Source Project: netbeans   Source File: CodeCommentAction.java    License: 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 Project: netbeans   Source File: SetProperty.java    License: 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 Project: netbeans   Source File: WhereUsedQueryElement.java    License: 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 Project: NBANDROID-V2   Source File: AddDependencyPanel.java    License: 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 Project: netbeans   Source File: GlyphGutter.java    License: 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
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 Project: org.alloytools.alloy   Source File: OurSyntaxDocument.java    License: 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 Project: netbeans   Source File: BaseDocument.java    License: 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 Project: netbeans   Source File: SpringXMLConfigCompletionItem.java    License: 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 13
Source Project: netbeans   Source File: GenerateJavadocAction.java    License: 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 14
Source Project: netbeans   Source File: DocPositionRegion.java    License: 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 15
/** 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 16
Source Project: netbeans   Source File: Utilities.java    License: 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 17
Source Project: netbeans   Source File: CompletionContext.java    License: 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 18
Source Project: netbeans   Source File: AnnotationView.java    License: 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 19
Source Project: netbeans   Source File: PUCompletionProvider.java    License: 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 20
Source Project: org.alloytools.alloy   Source File: SwingLogPanel.java    License: 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 21
Source Project: netbeans   Source File: BaseDocument.java    License: 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 22
Source Project: openjdk-8-source   Source File: MultiTextUI.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invokes the <code>modelToView</code> method on each UI handled by this object.
 *
 * @return the value obtained from the first UI, which is
 * the UI obtained from the default <code>LookAndFeel</code>
 */
public Rectangle modelToView(JTextComponent a, int b, Position.Bias c)
        throws BadLocationException {
    Rectangle returnValue =
        ((TextUI) (uis.elementAt(0))).modelToView(a,b,c);
    for (int i = 1; i < uis.size(); i++) {
        ((TextUI) (uis.elementAt(i))).modelToView(a,b,c);
    }
    return returnValue;
}
 
Example 23
Source Project: netbeans   Source File: SaasClientCodeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
protected void updateVariableNames(List<ParameterInfo> params) {
    nFinder.addPattern(VAR_NAMES_RESULT_DECL, new Integer(0));
    try {
        String text = getTargetDocument().getText(0, getTargetDocument().getLength());
        nFinder.updateVariableDecl(text, params);
        nFinder.updateVariableDecl(text, VAR_NAMES_RESULT_DECL);
    } catch (BadLocationException ex) {}
}
 
Example 24
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 25
Source Project: jdk8u-jdk   Source File: bug7003777.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            JTextPane pane = new JTextPane();

            pane.setContentType("text/html");

            for (String testString : TEST_STRINGS) {
                pane.setText(testString);

                String parsedText;

                try {
                    parsedText = pane.getDocument().getText(0, pane.getDocument().getLength());
                } catch (BadLocationException e) {
                    throw new RuntimeException("The test failed.", e);
                }

                if (parsedText.charAt(0) != '\n') {
                    throw new RuntimeException("The first char should be \\n");
                }

                parsedText = parsedText.substring(1);

                if (!testString.equals(parsedText)) {
                    throw new RuntimeException("The '" + testString +
                            "' string wasn't parsed correctly. Parsed value is '" + parsedText + "'");
                }
            }
        }
    });
}
 
Example 26
Source Project: darklaf   Source File: ColorValueFormatter.java    License: MIT License 5 votes vote down vote up
@Override
public void insertString(final FilterBypass fb, final int offset,
                         final String text, final AttributeSet set) throws BadLocationException {
    if (isValid(fb.getDocument().getLength() + text.length())
        && isValid(text)) {
        StringBuilder newText = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
        newText.insert(offset, text);
        if (hex || isValidValue(newText.toString())) {
            fb.insertString(offset, text.toUpperCase(ENGLISH), set);
            commit();
            return;
        }
    }
    error();
}
 
Example 27
Source Project: netbeans   Source File: ShowGoldenFiles.java    License: Apache License 2.0 5 votes vote down vote up
private static List<HighlightImpl> parse(StyledDocument doc, File highlights) throws IOException, ParseException, BadLocationException {
    if (!highlights.exists())
        return Collections.emptyList();
    
    BufferedReader bis = new BufferedReader(new InputStreamReader(new FileInputStream(highlights)));
    List<HighlightImpl> result = new ArrayList<HighlightImpl>();
    String line = null;
    
    while ((line = bis.readLine()) != null) {
        result.add(HighlightImpl.parse(doc, line));
    }
    
    return result;
}
 
Example 28
Source Project: netbeans   Source File: Occurrences.java    License: Apache License 2.0 5 votes vote down vote up
public static List<Occurrence> getPropertyOccurrences(final RenamedProperty renamedProperty, JavaSource js, final SpringScope scope) throws IOException {
    final List<Occurrence> result = new ArrayList<Occurrence>();
    final Set<File> processed = new HashSet<File>();

    js.runUserActionTask(new Task<CompilationController>() {

        @Override
        public void run(final CompilationController cc) throws Exception {
            cc.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            for (SpringConfigModel model : scope.getAllConfigModels()) {
                model.runDocumentAction(new Action<DocumentAccess>() {
                    public void run(DocumentAccess docAccess) {
                        File file = docAccess.getFile();
                        if (processed.contains(file)) {
                            return;
                        }
                        processed.add(file);
                        try {
                            new PropertyRefFinder(docAccess, cc, renamedProperty).addOccurrences(result);
                        } catch (BadLocationException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                    
                });
            }
        }
    }, true);
    
    return result;
}
 
Example 29
Source Project: netbeans   Source File: PropertyElementItem.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doSubstituteText(JTextComponent c, BaseDocument d, String text) throws BadLocationException {
    if (namespaceCreator != null) {
        try {
            String s = namespaceCreator.call();
            if (!"fx".equals(s)) {
                text = text.replace("fx:", s + ":");
            }
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    super.doSubstituteText(c, d, text);
}
 
Example 30
Source Project: netbeans   Source File: Utilities.java    License: Apache License 2.0 5 votes vote down vote up
/** Get the selection or identifier at the current caret position */
public static String getSelectionOrIdentifier(JTextComponent c) {
    try {
        return getSelectionOrIdentifier(c, c.getCaret().getDot());
    } catch (BadLocationException e) {
        return null;
    }
}