类javax.swing.text.BadLocationException源码实例Demo

下面列出了怎么用javax.swing.text.BadLocationException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: netbeans   文件: HyperlinkImpl.java
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;
}
 
源代码2 项目: netbeans   文件: FoldHierarchyTransactionImpl.java
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";
        }
    }
}
 
源代码3 项目: LGoodDatePicker   文件: JIntegerTextField.java
@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();
    }
}
 
源代码4 项目: netbeans   文件: CodeCommentAction.java
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);
    }
}
 
源代码5 项目: netbeans   文件: SetProperty.java
@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;
}
 
源代码6 项目: netbeans   文件: WhereUsedQueryElement.java
@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
    }
}
 
源代码7 项目: NBANDROID-V2   文件: AddDependencyPanel.java
/**
 * 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);
    }
}
 
源代码8 项目: netbeans   文件: GlyphGutter.java
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;
}
 
源代码9 项目: spotbugs   文件: SourceCodeDisplay.java
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;
    }
}
 
源代码10 项目: org.alloytools.alloy   文件: OurSyntaxDocument.java
/**
 * 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);
    }
}
 
源代码11 项目: netbeans   文件: BaseDocument.java
/** 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);
        }
    }
 
源代码12 项目: netbeans   文件: SpringXMLConfigCompletionItem.java
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);
            }
        }
    });
}
 
源代码13 项目: netbeans   文件: GenerateJavadocAction.java
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();
    }
}
 
源代码14 项目: netbeans   文件: DocPositionRegion.java
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];
}
 
源代码15 项目: openjdk-jdk9   文件: CheckAttributedTree.java
/** 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();
    }
}
 
源代码16 项目: netbeans   文件: Utilities.java
/**
 * @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;
}
 
源代码17 项目: netbeans   文件: CompletionContext.java
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);
    }
}
 
源代码18 项目: netbeans   文件: AnnotationView.java
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;
}
 
源代码19 项目: netbeans   文件: PUCompletionProvider.java
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;
}
 
源代码20 项目: org.alloytools.alloy   文件: SwingLogPanel.java
/**
 * 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();
    }
}
 
源代码21 项目: netbeans   文件: BaseDocument.java
/**
 * 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();
    }
}
 
源代码22 项目: openjdk-8-source   文件: MultiTextUI.java
/**
 * 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;
}
 
源代码23 项目: netbeans   文件: SaasClientCodeGenerator.java
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) {}
}
 
源代码24 项目: hortonmachine   文件: MapcalcController.java
protected void insertTextToFunctionArea( String newText ) {
    // AttributeSet attrs=((StyledEditorKit)_functionArea.getEditorKit()).getInputAttributes();
    try {
        _functionArea.getDocument().insertString(_functionArea.getCaretPosition(), newText, null);
    } catch (BadLocationException e) {
        addTextToFunctionArea(newText);
    }
}
 
源代码25 项目: jdk8u-jdk   文件: bug7003777.java
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 + "'");
                }
            }
        }
    });
}
 
源代码26 项目: darklaf   文件: ColorValueFormatter.java
@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();
}
 
源代码27 项目: netbeans   文件: ShowGoldenFiles.java
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;
}
 
源代码28 项目: netbeans   文件: Occurrences.java
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;
}
 
源代码29 项目: netbeans   文件: PropertyElementItem.java
@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);
}
 
源代码30 项目: netbeans   文件: Utilities.java
/** 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;
    }
}
 
 类所在包
 同包方法