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

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

源代码1 项目: netbeans   文件: GuardedSectionImpl.java
/** Deletes the text in the section.
 * @exception BadLocationException
 */
final void deleteText() throws BadLocationException {
    if (valid) {
        final StyledDocument doc = guards.getDocument();
        final BadLocationException[] blex = new BadLocationException[1];
        Runnable r = new Runnable() {
            public void run() {
                try {
                    int start = getStartPosition().getOffset();
                    if (start > 0 && "\n".equals(doc.getText(start - 1, 1))) { // NOI18N
                        start--;
                    }
                    doc.remove(start, getEndPosition().getOffset() - start + 1);
                } catch (BadLocationException ex) {
                    blex[0] = ex;
                }
            }
        };
        
        GuardedSectionsImpl.doRunAtomic(doc, r);
        
        if (blex[0] != null) {
            throw blex[0];
        }
    }
}
 
源代码2 项目: seaglass   文件: SeaGlassTextPaneUI.java
/**
 * Update the font in the default style of the document.
 *
 * @param font the new font to use or null to remove the font attribute
 *             from the document's style
 */
private void updateFont(Font font) {
    StyledDocument doc = (StyledDocument)getComponent().getDocument();
    Style style = doc.getStyle(StyleContext.DEFAULT_STYLE);

    if (style == null) {
        return;
    }

    if (font == null) {
        style.removeAttribute(StyleConstants.FontFamily);
        style.removeAttribute(StyleConstants.FontSize);
        style.removeAttribute(StyleConstants.Bold);
        style.removeAttribute(StyleConstants.Italic);
    } else {
        StyleConstants.setFontFamily(style, font.getName());
        StyleConstants.setFontSize(style, font.getSize());
        StyleConstants.setBold(style, font.isBold());
        StyleConstants.setItalic(style, font.isItalic());
    }
}
 
源代码3 项目: netbeans   文件: DocumentOpenClose.java
private StyledDocument retainExistingDocLA() { // Lock acquired mandatory
    switch (documentStatus) {
        case CLOSED:
            break;
        case RELOADING:
        case LOADING:
            cancelCloseLA(); // Cancel possible closing
            break;

        case OPENED:
            StyledDocument openDoc = getRefDocument();
            if (openDoc != null) { // Still opened
                // Check if a close attempt is not active and possibly cancel it
                cancelCloseLA();
                if (activeClose == null) {
                    return openDoc;
                }
            }
            break;

        default:
            throw invalidStatus();

    }
    return null;
}
 
源代码4 项目: netbeans   文件: JavaI18nFinderTest.java
@Before
public void setUp() throws Exception {
    FileSystem fs = FileUtil.createMemoryFileSystem();
    FileObject fo = fs.getRoot().createData("JFrame.java");
    
    source = convertStreamToString(getClass().getResourceAsStream("resources/JFrame.txt"));
    
    writeFile(source, fo);
    DataObject sourceDataObject = DataObject.find(fo);
    
    EditorCookie editorCookie = sourceDataObject.getCookie(EditorCookie.class);        
    if (editorCookie == null) {
        throw new IllegalArgumentException("I18N: Illegal data object type"+ sourceDataObject); // NOI18N
    }        
    StyledDocument document = editorCookie.getDocument();
    while(document == null) {
        document = editorCookie.openDocument();
    }        
                    
    instance = new JavaI18nFinder(document);
}
 
源代码5 项目: netbeans   文件: FormEditorSupport.java
@Override
protected void loadFromStreamToKit(StyledDocument doc, InputStream stream, EditorKit kit) throws IOException, BadLocationException {
    if (guardedEditor == null) {
        guardedEditor = new FormGEditor();
        GuardedSectionsFactory gFactory = GuardedSectionsFactory.find(((DataEditorSupport.Env) env).getMimeType());
        if (gFactory != null) {
            guardedProvider = gFactory.create(guardedEditor);
        }
    }
    
    if (guardedProvider != null) {
        guardedEditor.doc = doc;
        Charset c = FileEncodingQuery.getEncoding(this.getDataObject().getPrimaryFile());
        Reader reader = guardedProvider.createGuardedReader(stream, c);
        try {
            kit.read(reader, doc, 0);
        } finally {
            reader.close();
        }
    } else {
        super.loadFromStreamToKit(doc, stream, kit);
    }
}
 
private String convert(InputStream rtfDocumentInputStream) throws IOException {
  RTFEditorKit aRtfEditorkit = new RTFEditorKit();

  StyledDocument styledDoc = new DefaultStyledDocument();

  String textDocument;

  try {
    aRtfEditorkit.read(rtfDocumentInputStream, styledDoc, 0);

    textDocument = styledDoc.getText(0, styledDoc.getLength());
  } catch (BadLocationException e) {
    throw new IOException("Error during parsing");
  }

  return textDocument;
}
 
源代码7 项目: netbeans   文件: PositionBounds.java
public void resolvePositions() throws BadLocationException {
    StyledDocument doc = guards.getDocument();

    if (begin instanceof UnresolvedPosition) {
        begin = doc.createPosition(begin.getOffset());
    } else if (begin instanceof BiasedPosition) {
        ((BiasedPosition) begin).resolve(doc);
    }

    if (end instanceof UnresolvedPosition) {
        end = doc.createPosition(end.getOffset());
    } else if (end instanceof BiasedPosition) {
        ((BiasedPosition) end).resolve(doc);
    }
    assertPositionBounds();
}
 
源代码8 项目: netbeans   文件: MergePane.java
void addHighlight (StyledDocument doc, int line1, int line2, final java.awt.Color color) {
    if (line1 > 0) {
        --line1;
    }
    SimpleAttributeSet attrs = new SimpleAttributeSet();
    StyleConstants.setBackground(attrs, color);
    attrs.addAttribute(HighlightsContainer.ATTR_EXTENDS_EOL, Boolean.TRUE);
    int startOffset = getRowStartFromLineOffset(doc, line1);
    int endOffset = getRowStartFromLineOffset(doc, line2);
    synchronized (highlights) {
        ListIterator<HighLight> it = highlights.listIterator();
        HighLight toAdd = new HighLight(startOffset, endOffset, attrs);
        while (it.hasNext()) {
            HighLight highlight = it.next();
            if (highlight.contains(startOffset)) {
                it.remove();
                break;
            } else if (highlight.precedes(startOffset)) {
                it.previous();
                break;
            }
        }
        it.add(toAdd);
    }
    fireHilitingChanged();
}
 
源代码9 项目: mzmine2   文件: ResultsTextPane.java
public ResultsTextPane(StyledDocument doc) {
  super(doc);
  createStyles();
  setEditorKit(JTextPane.createEditorKitForContentType("text/html"));
  setEditable(false);
  addHyperlinkListener(new HyperlinkListener() {
    @Override
    public void hyperlinkUpdate(HyperlinkEvent e) {
      if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
        if (Desktop.isDesktopSupported()) {
          try {
            Desktop.getDesktop().browse(e.getURL().toURI());
          } catch (IOException | URISyntaxException e1) {
            e1.printStackTrace();
          }
        }
      }
    }
  });
}
 
源代码10 项目: binnavi   文件: BaseTypeTableCellRenderer.java
private static void generateDocument(
    final TypeInstance instance, final boolean renderData, final StyledDocument document) {
  switch (instance.getBaseType().getCategory()) {
    case ARRAY:
      renderArray(instance, document, renderData);
      break;
    case ATOMIC:
      renderAtomic(instance, document, renderData);
      break;
    case POINTER:
      renderPointer(instance, document);
      break;
    case STRUCT:
      renderStruct(instance, document, renderData);
      break;
    default:
      break;
  }
}
 
源代码11 项目: uima-uimaj   文件: CasAnnotationViewer.java
/**
 * Do bold face by spans.
 */
private void doBoldFaceBySpans() {
  if (this.boldFaceSpans == null || this.boldFaceSpans.length == 0) {
    return;
  }
  int docLength = this.cas.getDocumentText().length();
  int spanLength = this.boldFaceSpans.length - (this.boldFaceSpans.length % 2);
  int i = 0;
  while (i < spanLength) {
    int begin = this.boldFaceSpans[i];
    int end = this.boldFaceSpans[i + 1];
    if (begin >= 0 && begin <= docLength && end >= 0 && end <= docLength && begin < end) {
      MutableAttributeSet attrs = new SimpleAttributeSet();
      StyleConstants.setBold(attrs, true);
      StyledDocument doc = (StyledDocument) this.textPane.getDocument();
      doc.setCharacterAttributes(begin, end - begin, attrs, false);
    }
    i += 2;
  }
}
 
private static boolean isRefactorableEditorElement(final Node node) {
    final AtomicBoolean result = new AtomicBoolean(false);
    Mutex.EVENT.readAccess(new Runnable() {

        @Override
        public void run() {
            EditorCookie ec = getEditorCookie(node);
            if (isFromEditor(ec)) {
                //check if there's css code at the offset
                final StyledDocument document = ec.getDocument();
                JEditorPane pane = ec.getOpenedPanes()[0];
                final int caret = pane.getCaretPosition();
                document.render(new Runnable() {

                    @Override
                    public void run() {
                        result.set(null != LexerUtils.getTokenSequence(document, caret, CssTokenId.language(), true));
                    }
                });
            }
        }
        
    });

    return result.get();
}
 
源代码13 项目: netbeans   文件: NbToolTip.java
private boolean isDocumentValid() {
    DataObject dob = NbEditorUtilities.getDataObject(doc);
    if (dob != null) {
        EditorCookie ec = dob.getCookie(EditorCookie.class);
        if (ec != null) {
            StyledDocument openedDoc;
            try {
                openedDoc = ec.openDocument();
            } catch (IOException e) {
                openedDoc = null; // should return in next if stmt
            }
            
            return (openedDoc == doc);
        }
    }
    return false;
}
 
源代码14 项目: netbeans   文件: GuardedSectionImpl.java
/** Marks or unmarks the section as guarded.
 * @param doc The styled document where this section placed in.
 * @param bounds The rangeof text which should be marked or unmarked.
 * @param mark true means mark, false unmark.
 */
void markGuarded(StyledDocument doc, PositionBounds bounds, boolean mark) {
    int begin = bounds.getBegin().getOffset();
    int end = bounds.getEnd().getOffset();
    
    if (end == doc.getLength() + 1) {
        end--;
    }
    GuardedRegionMarker marker = LineDocumentUtils.as(doc, GuardedRegionMarker.class);
    if (marker != null) {
        if (mark) {
            marker.protectRegion(begin, end - begin + 1);
        } else {
            marker.unprotectRegion(begin, end - begin + 1);
        }
    }
}
 
源代码15 项目: wpcleaner   文件: MWPaneSelectionManager.java
/**
 * Select previous occurrence of text. 
 */
public void selectPreviousOccurrence() {
  StyledDocument doc = textPane.getStyledDocument();
  int lastStart = Integer.MIN_VALUE;
  for (int pos = textPane.getSelectionStart(); pos > 0; pos = lastStart) {
    Element run = doc.getCharacterElement(pos - 1);
    lastStart = run.getStartOffset();
    MutableAttributeSet attr = (MutableAttributeSet) run.getAttributes();
    if ((attr != null) &&
        (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_TYPE) != null) &&
        (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_OCCURRENCE) != Boolean.FALSE)) {
      select(run);
      return;
    }
  }
  selectLastOccurrence();
}
 
源代码16 项目: netbeans   文件: SearchCompletionItem.java
@Override
public void defaultAction(final JTextComponent component) {
    Completion.get().hideCompletion();
    Completion.get().hideDocumentation();
    NbDocument.runAtomic((StyledDocument) component.getDocument(), new Runnable() {
        @Override
        public void run() {
            Document doc = component.getDocument();

            try {
                doc.remove(0, doc.getLength());
                doc.insertString(0, getText(), null);
            } catch (BadLocationException e) {
                Logger.getLogger(SearchCompletionItem.class.getName()).log(Level.FINE, null, e);
            }
        }
    });
}
 
源代码17 项目: 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;
}
 
源代码18 项目: netbeans   文件: WordCompletionItem.java
public void defaultAction(final JTextComponent component) {
    Completion.get().hideCompletion();
    Completion.get().hideDocumentation();
    NbDocument.runAtomic((StyledDocument) component.getDocument(), new Runnable() {
        public void run() {
            Document doc = component.getDocument();
            
            try {
                doc.remove(substituteOffset, component.getCaretPosition() - substituteOffset);
                doc.insertString(substituteOffset, getText(), null);
            } catch (BadLocationException e) {
                ErrorManager.getDefault().notify(e);
            }
        }
    });
}
 
源代码19 项目: netbeans   文件: XMLDataObjectMimeTypeTest.java
public void testForUnknownMime() throws Exception {
    
    
    X l = X.getLoader(X.class);
    l.getExtensions().addExtension(getName());
    AddLoaderManuallyHid.addRemoveLoader(l, true);
    
    try {
        setUp("content/unknown");
        EditorCookie cook = obj.getCookie(EditorCookie.class);
        StyledDocument doc = cook.openDocument();
        assertEquals("text/xml", doc.getProperty("mimeType"));
    } finally {
        AddLoaderManuallyHid.addRemoveLoader(l, false);
    }
}
 
public void testCallingFromAWTIsOk() throws Exception {
    StyledDocument doc = support.openDocument();
    doc.insertString(0, "Ble", null);
    
    assertTrue("Modified", support.isModified());
    
    class AWT implements Runnable {
        boolean success;
        
        public synchronized void run() {
            success = support.canClose();
        }
    }
    
    AWT b = new AWT();
    javax.swing.SwingUtilities.invokeAndWait(b);
    
    assertTrue("Ok, we managed to ask the question", b.success);
    
    if (ErrManager.messages.length() > 0) {
        fail("No messages should be reported: " + ErrManager.messages);
    }
}
 
源代码21 项目: netbeans   文件: GuardedSectionsImpl.java
/** Takes the section descriptors from the GuardedReader and
* fills the table 'sections', also marks as guarded all sections
* in the given document.
* @param is Where to take the guarded section descriptions.
* @param doc Where to mark guarded.
*/
void fillSections(AbstractGuardedSectionsProvider gr, List<GuardedSection> l, NewLine newLineType) {
    this.gr = GuardsSupportAccessor.DEFAULT.isUseReadersWritersOnSet(gr) ? gr : null;
    this.newLineType = newLineType;
    // XXX this should invalidate removed GS instances
    // XXX maybe would be useful to map new list to old list to keep track of valid instances as much as possible
    // XXX synchronize
    this.sections.clear();
    
    for (GuardedSection gs: l) {
        try {
            GuardedSectionImpl gsi = GuardsAccessor.DEFAULT.getImpl(gs);
            gsi.resolvePositions();
            sections.put(gs.getName(), gsi);
            StyledDocument doc = getDocument();
            gsi.markGuarded(doc);
        } catch (BadLocationException ex) {
            Logger.getLogger(GuardedSectionsImpl.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        }
    }
}
 
源代码22 项目: otroslogviewer   文件: FormatMessageDialogWorker.java
@Override
protected void done() {
  LOGGER.trace("Message details format and colors calculated, updating GUI");
  StyledDocument styledDocument = otrosJTextWithRulerScrollPane.getjTextComponent().getStyledDocument();
  try {
    styledDocument.remove(0, styledDocument.getLength());
  } catch (BadLocationException e) {
    LOGGER.error("Can't clear log events text  area", e);
  }
  if (!isCancelled()) {
    updateChanges(chunks);
  }
  LOGGER.trace("GUI updated");
}
 
源代码23 项目: netbeans   文件: DumpTokens.java
@SuppressWarnings("unchecked")
private List<Token> dumpTokens() throws IOException {
    Logger.getLogger(DumpTokens.class.getName()).info("Dumping tokens");
    DataObject dataObj = DataObject.find(FileUtil.toFileObject(file));
    EditorCookie ed = dataObj.getCookie(EditorCookie.class);

    StyledDocument sDoc = ed.openDocument();
    BaseDocument doc = (BaseDocument) sDoc;
    TokenHierarchy th = null;
    TokenSequence ts = null;
    int roundCount = 0;
    while ((th == null) || (ts == null)){
        th = TokenHierarchy.get(doc);
        if (th != null){
            ts = th.tokenSequence();
        }
        roundCount++;
        if (roundCount > 50){
            throw new AssertionError("Impossible to get token hierarchy " +roundCount+ "times");
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        }
        
    }
    try{
        Logger.getLogger(DumpTokens.class.getName()).info("Parsing token sequence");
        List<Token> tok = dumpTokens(ts);
        return tok;
    }catch(Exception e){
        e.printStackTrace();
    }
    return null;
}
 
源代码24 项目: MtgDesktopCompanion   文件: MagicTextPane.java
public void updateTextWithIcons() {

		textPane.setText(textPane.getText().replaceAll("(?m)^[ \t]*\r?\n", ""));
		Pattern p = Pattern.compile(CardsPatterns.MANA_PATTERN.getPattern());
		Matcher m = p.matcher(textPane.getText());

		String text = textPane.getText();
		StyleContext context = new StyleContext();
		StyledDocument document = new DefaultStyledDocument(context);

		Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);

		Style italic = context.addStyle("italicStyle", labelStyle);
		StyleConstants.setItalic(italic, true);

		int cumule = 0;
		try {
			document.insertString(0, text, null);
			while (m.find()) {
				Image ic = manaPanel.getManaSymbol(m.group());

				int width = 15;
				if (m.group().equals("{100}"))
					width = 30;

				JLabel label = new JLabel(new ImageIcon(ic.getScaledInstance(width, 15, Image.SCALE_DEFAULT)));
				label.setAlignmentY(SwingConstants.TOP);

				StyleConstants.setComponent(labelStyle, label);

				document.remove(m.start() + cumule, (m.end() - m.start()));
				document.insertString(m.start() + cumule, m.group(), labelStyle);
			}

			textPane.setDocument(document);
		} catch (BadLocationException e) {
			textPane.setText(text);
		}
	}
 
源代码25 项目: netbeans   文件: ComputeAnnotations.java
@Override
public void run(Result result, SchedulerEvent event) {
    cancel.set(false);
    
    CompilationInfo info = CompilationInfo.get(result);

    if (info.getChangedTree() != null) {
        //XXX: currently only method bodies are rebuilt.
        return ;
    }
    
    long start = System.currentTimeMillis();
    StyledDocument doc = (StyledDocument) result.getSnapshot().getSource().getDocument(false);

    if (doc == null) {
        return ;
    }
    
    List<IsOverriddenAnnotation> annotations = computeAnnotations(info, doc);

    if (cancel.get()) return ;
    
    AnnotationsHolder holder = AnnotationsHolder.get(info.getFileObject());

    if (holder != null) {
        holder.setNewAnnotations(annotations);
    }

    long end = System.currentTimeMillis();

    Logger.getLogger("TIMER").log(Level.FINE, "Is Overridden Annotations", new Object[] {info.getFileObject(), end - start});
}
 
源代码26 项目: netbeans   文件: PropertiesEditorSupport.java
/**
 * Called from the <code>EnvironmentListener</code>.
 */
final void updateDocumentProperty () {
    //Update document TitleProperty
    EditorCookie ec = getDataObject().getCookie(EditorCookie.class);
    if (ec != null) {
        StyledDocument doc = ec.getDocument();
        if (doc != null) {
            doc.putProperty(Document.TitleProperty,
            FileUtil.getFileDisplayName(getDataObject().getPrimaryFile()));
        }
    }
}
 
源代码27 项目: netbeans   文件: AnnotationView.java
private int getCurrentLine() {
    Document doc = pane.getDocument();
    int line = -1;
    
    if (doc instanceof StyledDocument && pane.getCaret() != null) {
        int offset = pane.getCaretPosition(); //TODO: AWT?
        line = NbDocument.findLineNumber((StyledDocument) doc, offset);
    }
    
    return line;
}
 
源代码28 项目: SikuliX1   文件: PythonIndentation.java
@Override
public int atEndOfLine(StyledDocument doc, int cpos, int start, String s, int sLen) {
  for (int i = cpos - start; i < sLen; i++) {
    if (doc.getCharacterElement(cpos).getName().equals(StyleConstants.ComponentElementName) || !isWhitespace(s.charAt(i))) {
      return i + start;
    }
    cpos++;
  }
  return -1;
}
 
源代码29 项目: dsworkbench   文件: AttackCalculationPanel.java
/**
 * Creates new form AttackSourcePanel
 */
AttackCalculationPanel() {
    initComponents();
    jXCollapsiblePane1.setLayout(new BorderLayout());
    jXCollapsiblePane1.add(jInfoScrollPane, BorderLayout.CENTER);
    jInfoTextPane.setText(GENERAL_INFO);
    StyledDocument doc = (StyledDocument) jTextPane1.getDocument();
    Style defaultStyle = doc.addStyle("Default", null);
    StyleConstants.setItalic(defaultStyle, true);
    StyleConstants.setFontFamily(defaultStyle, "SansSerif");
    dateFormat = new SimpleDateFormat("HH:mm:ss");
}
 
源代码30 项目: FancyBing   文件: GuiUtil.java
public static void addStyle(JTextPane textPane, String name,
                            Color foreground, Color background,
                            boolean bold)
{
    StyledDocument doc = textPane.getStyledDocument();
    StyleContext context = StyleContext.getDefaultStyleContext();
    Style def = context.getStyle(StyleContext.DEFAULT_STYLE);
    Style style = doc.addStyle(name, def);
    if (foreground != null)
        StyleConstants.setForeground(style, foreground);
    if (background != null)
        StyleConstants.setBackground(style, background);
    StyleConstants.setBold(style, bold);
}
 
 类所在包
 同包方法