javax.swing.text.StyledDocument#getText ( )源码实例Demo

下面列出了javax.swing.text.StyledDocument#getText ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: desktopclient-java   文件: LinkUtils.java
@Override
public void mouseClicked(MouseEvent e) {
    WebTextPane textPane = (WebTextPane) e.getComponent();
    StyledDocument doc = textPane.getStyledDocument();
    Element elem = doc.getCharacterElement(textPane.viewToModel(e.getPoint()));
    if (!elem.getAttributes().isDefined(URL_ATT_NAME))
        // not a link
        return;

    int len = elem.getEndOffset() - elem.getStartOffset();
    final String url;
    try {
        url = doc.getText(elem.getStartOffset(), len);
    } catch (BadLocationException ex) {
        LOGGER.log(Level.WARNING, "can't get URL", ex);
        return;
    }

    Runnable run = new Runnable() {
        @Override
        public void run() {
            WebUtils.browseSiteSafely(fixProto(url));
        }
    };
    new Thread(run, "Link Browser").start();
}
 
源代码2 项目: netbeans   文件: EditorContextImpl.java
/** return the offset of the first non-whitespace character on the line,
           or -1 when the line does not exist
 */
private static int findLineOffset(StyledDocument doc, int lineNumber) {
    int offset;
    try {
        offset = NbDocument.findLineOffset (doc, lineNumber - 1);
        int offset2 = NbDocument.findLineOffset (doc, lineNumber);
        try {
            String lineStr = doc.getText(offset, offset2 - offset);
            for (int i = 0; i < lineStr.length(); i++) {
                if (!Character.isWhitespace(lineStr.charAt(i))) {
                    offset += i;
                    break;
                }
            }
        } catch (BadLocationException ex) {
            // ignore
        }
    } catch (IndexOutOfBoundsException ioobex) {
        return -1;
    }
    return offset;
}
 
源代码3 项目: netbeans   文件: ImportDebugger.java
static String getText (Line l) throws Exception {
    EditorCookie ec = (EditorCookie) l.getDataObject ().
        getCookie (EditorCookie.class);
    StyledDocument doc = ec.openDocument ();
    if (doc == null) return "";
    int off = NbDocument.findLineOffset (doc, l.getLineNumber ());
    int len = NbDocument.findLineOffset (doc, l.getLineNumber () + 1) - 
        off - 1;
    return doc.getText (off, len);
}
 
源代码4 项目: otroslogviewer   文件: SearchAction.java
private void scrollToSearchResult(ArrayList<String> toHighlight, JTextPane textPane) {
  if (toHighlight.size() == 0) {
    return;
  }
  try {
    StyledDocument logDetailsDocument = textPane.getStyledDocument();
    String text = logDetailsDocument.getText(0, logDetailsDocument.getLength());
    String string = toHighlight.get(0);
    textPane.setCaretPosition(Math.max(text.indexOf(string), 0));
  } catch (BadLocationException e) {
    LOGGER.warn("Cant scroll to content, wrong location: " + e.getMessage());
  }
}
 
源代码5 项目: netbeans   文件: Utilities.java
public static String getAsString(String file) {
    String result;
    try {
        FileObject testFile = Repository.getDefault().findResource(file);
        DataObject DO = DataObject.find(testFile);
        
        EditorCookie ec=(EditorCookie)(DO.getCookie(EditorCookie.class));
        StyledDocument doc=ec.openDocument();
        result=doc.getText(0, doc.getLength());
        //            result=Common.unify(result);
    } catch (Exception e){
        throw new AssertionFailedErrorException(e);
    }
    return result;
}
 
源代码6 项目: netbeans   文件: HtmlEditorSupport.java
private String getDocumentText() {
    String text = "";
    try {
        StyledDocument doc = getDocument();
        if (doc != null) {
            text = doc.getText(doc.getStartPosition().getOffset(), doc.getLength());
        }
    } catch (BadLocationException e) {
        Logger.getLogger("global").log(Level.WARNING, null, e);
    }
    return text;
}
 
源代码7 项目: groovy   文件: GroovyFilter.java
public void actionPerformed(ActionEvent ae) {
    JTextComponent tComp = (JTextComponent) ae.getSource();
    if (tComp.getDocument() instanceof StyledDocument) {
        doc = (StyledDocument) tComp.getDocument();
        try {
            doc.getText(0, doc.getLength(), segment);
        }
        catch (Exception e) {
            // should NEVER reach here
            e.printStackTrace();
        }
        int offset = tComp.getCaretPosition();
        int index = findTabLocation(offset);
        buffer.delete(0, buffer.length());
        buffer.append('\n');
        if (index > -1) {
            for (int i = 0; i < index + 4; i++) {
                buffer.append(' ');
            }
        }
        try {
            doc.insertString(offset, buffer.toString(),
                    doc.getDefaultRootElement().getAttributes());
        }
        catch (BadLocationException ble) {
            ble.printStackTrace();
        }
    }
}
 
源代码8 项目: netbeans   文件: PositionBounds.java
/** Finds the text contained in this range.
* @return the text
* @exception IOException if any I/O problem occurred during document loading (if that was necessary)
* @exception BadLocationException if the positions are out of the bounds of the document
*/
public String getText() throws BadLocationException, IOException {
    StyledDocument doc = begin.getCloneableEditorSupport().openDocument();
    int p1 = begin.getOffset();
    int p2 = end.getOffset();

    return doc.getText(p1, p2 - p1);
}
 
源代码9 项目: netbeans   文件: ReloadTest.java
public void testRefreshProblem46885 () throws Exception {
    StyledDocument doc = support.openDocument ();
    
    doc.insertString (0, "A text", null);
    support.saveDocument ();
    
    content = "New";
    propL.firePropertyChange (CloneableEditorSupport.Env.PROP_TIME, null, null);
    
    waitAWT ();
    Task reloadTask = support.reloadDocument();
    reloadTask.waitFinished();
    
    String s = doc.getText (0, doc.getLength ());
    assertEquals ("Text has been updated", content, s);
    

    long oldtime = System.currentTimeMillis ();
    Thread.sleep(300);
    err.info("Document modified");
    doc.insertString (0, "A text", null);
    err.info("Document about to save");
    support.saveDocument ();
    err.info("Document saved");
    s = doc.getText (0, doc.getLength ());

    err.info("Current content: " + s);
    content = "NOT TO be loaded";
    propL.firePropertyChange (CloneableEditorSupport.Env.PROP_TIME, null, new Date (oldtime));
    
    waitAWT ();
    
    String s1 = doc.getText (0, doc.getLength ());
    err.info("New content: " + s1);
    assertEquals ("Text has not been updated", s, s1);
}
 
源代码10 项目: netbeans   文件: ToolTipAnnotation.java
private static String getIdentifier(final StyledDocument doc, final JEditorPane ep, final int offset) {
    String t = null;
    if (ep.getCaret() != null) { // #255228
        if ((ep.getSelectionStart() <= offset) && (offset <= ep.getSelectionEnd())) {
            t = ep.getSelectedText();
        }
        if (t != null) {
            return t;
        }
    }
    int line = NbDocument.findLineNumber(doc, offset);
    int col = NbDocument.findLineColumn(doc, offset);
    Element lineElem = NbDocument.findLineRootElement(doc).getElement(line);
    try {
        if (lineElem == null) {
            return null;
        }
        int lineStartOffset = lineElem.getStartOffset();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        if (col + 1 >= lineLen) {
            // do not evaluate when mouse hover behind the end of line (112662)
            return null;
        }
        t = doc.getText(lineStartOffset, lineLen);
        return getExpressionToEvaluate(t, col);
    } catch (BadLocationException e) {
        return null;
    }
}
 
源代码11 项目: netbeans   文件: TplEditorSupport.java
private String getDocumentText() {
    String text = "";
    try {
        StyledDocument doc = getDocument();
        if (doc != null) {
            text = doc.getText(doc.getStartPosition().getOffset(), doc.getLength());
        }
    } catch (BadLocationException e) {
        Logger.getLogger("global").log(Level.WARNING, null, e);
    }
    return text;
}
 
源代码12 项目: netbeans   文件: WebUrlHyperlinkSupport.java
static void register(final JTextPane pane) {
    final StyledDocument doc = pane.getStyledDocument();
    String text = "";
    try {
        text = doc.getText(0, doc.getLength());
    } catch (BadLocationException ex) {
        Support.LOG.log(Level.SEVERE, null, ex);
    }
    final int[] boundaries = findBoundaries(text);
    if ((boundaries != null) && (boundaries.length != 0)) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Style defStyle = StyleContext.getDefaultStyleContext()
                                 .getStyle(StyleContext.DEFAULT_STYLE);
                final Style hlStyle = doc.addStyle("regularBlue-url", defStyle);      //NOI18N
                hlStyle.addAttribute(HyperlinkSupport.URL_ATTRIBUTE, new UrlAction());
                StyleConstants.setForeground(hlStyle, UIUtils.getLinkColor());
                StyleConstants.setUnderline(hlStyle, true);
                for (int i = 0; i < boundaries.length; i+=2) {
                    doc.setCharacterAttributes(boundaries[i], boundaries[i + 1] - boundaries[i], hlStyle, true);
                }
                pane.removeMouseListener(getUrlMouseListener());
                pane.addMouseListener(getUrlMouseListener());
            }
        });
    }
}
 
源代码13 项目: binnavi   文件: BaseTypeTableCellRenderer.java
public static FormattedCharacterBuffer convertDocumentToFormattedCharacterBuffer(
    final StyledDocument document, Font font, int desiredWidth) {
  // The following code calculates the number of rows and the number of columns required for the
  // FormattedCharacterBuffer.
  int width = desiredWidth, height = 0;
  String text = "";
  try {
    text = document.getText(0, document.getLength());
  } catch (BadLocationException e) {
    // Cannot happen.
  }
  String[] chunks = text.split("\n");
  height = chunks.length;
  for (String line : chunks) {
    // The +1 is necessary because we wish to store the newline characters in the
    // FormattedCharacterBuffer.
    width = Math.max(width, line.length() + 1);
  }
  // Height & width is calculated, now create the buffer.
  FormattedCharacterBuffer result = new FormattedCharacterBuffer(height, width);
  int lineindex = 0, columnindex = 0;
  for (int index = 0; index < document.getLength(); ++index) {
    if (text.charAt(index) != '\n') {
      AttributeSet attributes = document.getCharacterElement(index).getAttributes();
      Color foreground =
          document.getForeground(attributes);
      Color background =
          document.getBackground(attributes);

      columnindex++;
      result.setAt(lineindex, columnindex, text.charAt(index), font, foreground, background);
    } else {
      columnindex = 0;
      lineindex++;
    }
  }
  return result;
}
 
源代码14 项目: netbeans   文件: AbstractTestUtil.java
/** Converts DataObject to String.
 */
public static String dataObjectToString(DataObject dataObject) throws IOException, BadLocationException {
    EditorCookie editorCookie = (EditorCookie) dataObject.getCookie(EditorCookie.class);
    
    if (editorCookie != null) {
        StyledDocument document = editorCookie.openDocument();
        if (document != null) {
            return  document.getText(0, document.getLength());
        }
    }
    return null;
}
 
源代码15 项目: binnavi   文件: BaseTypeTableCellRenderer.java
public static String renderText(final TypeInstance instance) {
  final StyledDocument document = new DefaultStyledDocument();
  generateDocument(instance, false, document);
  try {
    return document.getText(0, document.getLength());
  } catch (final BadLocationException exception) {
    CUtilityFunctions.logException(exception);
  }
  return "";
}
 
源代码16 项目: nb-springboot   文件: CfgPropsDocAndTooltipQuery.java
@Override
protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) {
    final StyledDocument styDoc = (StyledDocument) document;
    Element lineElement = styDoc.getParagraphElement(caretOffset);
    int lineStartOffset = lineElement.getStartOffset();
    int lineEndOffset = lineElement.getEndOffset();
    try {
        String line = styDoc.getText(lineStartOffset, lineEndOffset - lineStartOffset);
        if (line.endsWith("\n")) {
            line = line.substring(0, line.length() - 1);
        }
        if (showTooltip) {
            logger.log(FINER, "Tooltip on: {0}", line);
        } else {
            logger.log(FINER, "Documentation on: {0}", line);
        }
        if (!line.contains("#")) {
            //property name extraction from line
            Matcher matcher = PATTERN_PROP_NAME.matcher(line);
            if (matcher.matches()) {
                String propPrefix = matcher.group(1);
                ConfigurationMetadataProperty propMeta = sbs.getPropertyMetadata(propPrefix);
                if (propMeta != null) {
                    if (showTooltip) {
                        final JToolTip toolTip = new JToolTip();
                        toolTip.setTipText(Utils.shortenJavaType(propMeta.getType()));
                        completionResultSet.setToolTip(toolTip);
                    } else {
                        completionResultSet.setDocumentation(new CfgPropCompletionDocumentation(propMeta));
                    }
                }
            }
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
    completionResultSet.finish();
}
 
源代码17 项目: nb-springboot   文件: FileObjectCompletionItem.java
@Override
public void defaultAction(JTextComponent jtc) {
    logger.log(Level.FINER, "Accepted file object completion: {0}", FileUtil.getFileDisplayName(fileObj));
    try {
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        // calculate the amount of chars to remove (by default from dot up to caret position)
        int lenToRemove = caretOffset - dotOffset;
        if (overwrite) {
            // NOTE: the editor removes by itself the word at caret when ctrl + enter is pressed
            // the document state here is different from when the completion was invoked thus we have to
            // find again the offset of the equal sign in the line
            Element lineElement = doc.getParagraphElement(caretOffset);
            String line = doc.getText(lineElement.getStartOffset(), lineElement.getEndOffset() - lineElement.getStartOffset());
            int equalSignIndex = line.indexOf('=');
            int colonIndex = line.indexOf(':');
            int commaIndex = line.indexOf(',', dotOffset - lineElement.getStartOffset());
            if (equalSignIndex >= 0 && dotOffset < equalSignIndex) {
                // from dot to equal sign
                lenToRemove = lineElement.getStartOffset() + equalSignIndex - dotOffset;
            } else if (colonIndex >= 0 && dotOffset < colonIndex) {
                // from dot to colon
                lenToRemove = lineElement.getStartOffset() + colonIndex - dotOffset;
            } else if (commaIndex >= 0) {
                // from dot to comma
                lenToRemove = lineElement.getStartOffset() + commaIndex - dotOffset;
            } else {
                // from dot to end of line (except line terminator)
                lenToRemove = lineElement.getEndOffset() - 1 - dotOffset;
            }
        }
        // remove characters from dot then insert new text
        doc.remove(dotOffset, lenToRemove);
        if (fileObj.isRoot()) {
            logger.log(Level.FINER, "Adding filesystem root and continuing completion");
            doc.insertString(dotOffset, getText(), null);
        } else if (fileObj.isFolder()) {
            logger.log(Level.FINER, "Adding folder and continuing completion");
            doc.insertString(dotOffset, getText().concat("/"), null);
        } else {
            logger.log(Level.FINER, "Adding file and finishing completion");
            doc.insertString(dotOffset, getText(), null);
            Completion.get().hideAll();
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
源代码18 项目: netbeans   文件: ToolTipAnnotation.java
private static String getIdentifier (
    StyledDocument doc, 
    JEditorPane ep, 
    int offset
) {
    String t = null;
    if ( (ep.getSelectionStart () <= offset) &&
         (offset <= ep.getSelectionEnd ())
    )   t = ep.getSelectedText ();
    if (t != null) return t;
    
    int line = NbDocument.findLineNumber (
        doc,
        offset
    );
    int col = NbDocument.findLineColumn (
        doc,
        offset
    );
    try {
        Element lineElem = 
            NbDocument.findLineRootElement (doc).
            getElement (line);

        if (lineElem == null) return null;
        int lineStartOffset = lineElem.getStartOffset ();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        t = doc.getText (lineStartOffset, lineLen);
        lineLen = t.length ();
        int identStart = col;
        while ( (identStart > 0) && 
                (t.charAt (identStart - 1) != '"')
        ) {
            identStart--;
        }
        int identEnd = Math.max (col, 1);
        while ( (identEnd < lineLen) && 
                (t.charAt (identEnd - 1) != '"')
        ) {
            identEnd++;
        }

        if (identStart == identEnd) return null;
        return t.substring (identStart, identEnd - 1);
    } catch (BadLocationException e) {
        return null;
    }
}
 
源代码19 项目: nb-springboot   文件: JavaTypeCompletionItem.java
@Override
public void defaultAction(JTextComponent jtc) {
    logger.log(Level.FINER, "Accepted java type completion: {0} {1}", new Object[]{elementKind.toString(), name});
    try {
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        // calculate the amount of chars to remove (by default from dot up to caret position)
        int lenToRemove = caretOffset - dotOffset;
        if (overwrite) {
            // NOTE: the editor removes by itself the word at caret when ctrl + enter is pressed
            // the document state here is different from when the completion was invoked thus we have to
            // find again the offset of the equal sign in the line
            Element lineElement = doc.getParagraphElement(caretOffset);
            String line = doc.getText(lineElement.getStartOffset(), lineElement.getEndOffset() - lineElement.getStartOffset());
            int equalSignIndex = line.indexOf('=');
            int colonIndex = line.indexOf(':');
            int commaIndex = line.indexOf(',', dotOffset - lineElement.getStartOffset());
            if (equalSignIndex >= 0 && dotOffset < equalSignIndex) {
                // from dot to equal sign
                lenToRemove = lineElement.getStartOffset() + equalSignIndex - dotOffset;
            } else if (colonIndex >= 0 && dotOffset < colonIndex) {
                // from dot to colon
                lenToRemove = lineElement.getStartOffset() + colonIndex - dotOffset;
            } else if (commaIndex >= 0) {
                // from dot to comma
                lenToRemove = lineElement.getStartOffset() + commaIndex - dotOffset;
            } else {
                // from dot to end of line (except line terminator)
                lenToRemove = lineElement.getEndOffset() - 1 - dotOffset;
            }
        }
        // remove characters from dot then insert new text
        doc.remove(dotOffset, lenToRemove);
        if (isKeyCompletion) {
            // insert and continue completion
            doc.insertString(dotOffset, name.concat("="), null);
        } else {
            // insert and close the code completion box
            doc.insertString(dotOffset, name, null);
            Completion.get().hideAll();
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
源代码20 项目: netbeans   文件: AbstractTestUtil.java
/**
     * Enbles <code>enable = true</code>  or disables <code>enable = false</code> the module.
     */
    public static void switchModule(String codeName, boolean enable) throws Exception {
        String statusFile = "Modules/" + codeName.replace('.', '-') + ".xml";
        ModuleInfo mi = getModuleInfo(codeName);
/*
        FileObject fo = findFileObject(statusFile);
        Document document = XMLUtil.parse(new InputSource(fo.getInputStream()), false, false, null, EntityCatalog.getDefault());
        //Document document = XMLUtil.parse(new InputSource(data.getPrimaryFile().getInputStream()), false, false, null, EntityCatalog.getDefault());
        NodeList list = document.getElementsByTagName("param");
 
        for (int i = 0; i < list.getLength(); i++) {
            Element ele = (Element) list.item(i);
            if (ele.getAttribute("name").equals("enabled")) {
                ele.getFirstChild().setNodeValue(enable ? "true" : "false");
                break;
            }
        }
 
        FileLock lock = fo.lock();
        OutputStream os = fo.getOutputStream(lock);
        XMLUtil.write(document, os, "UTF-8");
        lock.releaseLock();
        os.close();
 */
        
        // module is switched
        if (mi.isEnabled() == enable) {
            return;
        }
        
        DataObject data = findDataObject(statusFile);
        EditorCookie ec = (EditorCookie) data.getCookie(EditorCookie.class);
        StyledDocument doc = ec.openDocument();
        
        // Change parametr enabled
        String stag = "<param name=\"enabled\">";
        String etag = "</param>";
        String enabled = enable ? "true" : "false";
        String result;
        
        String str = doc.getText(0,doc.getLength());
        int sindex = str.indexOf(stag);
        int eindex = str.indexOf(etag, sindex);
        if (sindex > -1 && eindex > sindex) {
            result = str.substring(0, sindex + stag.length()) + enabled + str.substring(eindex);
            //System.err.println(result);
        } else {
            //throw new IllegalStateException("Invalid format of: " + statusFile + ", missing parametr 'enabled'");
            // Probably autoload module
            return;
        }
        
        // prepare synchronization and register listener
        final Waiter waiter = new Waiter();
        final PropertyChangeListener pcl = new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("enabled")) {
                    waiter.notifyFinished();
                }
            }
        };
        mi.addPropertyChangeListener(pcl);
        
        // save document
        doc.remove(0,doc.getLength());
        doc.insertString(0,result,null);
        ec.saveDocument();
        
        // wait for enabled propety change and remove listener
        waiter.waitFinished();
        mi.removePropertyChangeListener(pcl);
    }