Java Code Examples for javax.swing.text.StyledDocument

The following examples show how to use javax.swing.text.StyledDocument. 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: GuardedSectionImpl.java    License: Apache License 2.0 6 votes vote down vote up
/** 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];
        }
    }
}
 
Example 2
Source Project: seaglass   Source File: SeaGlassTextPaneUI.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 3
Source Project: netbeans   Source File: DocumentOpenClose.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source Project: netbeans   Source File: JavaI18nFinderTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 5
Source Project: netbeans   Source File: FormEditorSupport.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 6
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;
}
 
Example 7
Source Project: netbeans   Source File: PositionBounds.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 8
Source Project: netbeans   Source File: MergePane.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 9
Source Project: mzmine2   Source File: ResultsTextPane.java    License: GNU General Public License v2.0 6 votes vote down vote up
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();
          }
        }
      }
    }
  });
}
 
Example 10
Source Project: binnavi   Source File: BaseTypeTableCellRenderer.java    License: Apache License 2.0 6 votes vote down vote up
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;
  }
}
 
Example 11
Source Project: uima-uimaj   Source File: CasAnnotationViewer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
  }
}
 
Example 12
Source Project: netbeans   Source File: CssActionsImplementationProvider.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 13
Source Project: netbeans   Source File: NbToolTip.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 14
Source Project: netbeans   Source File: GuardedSectionImpl.java    License: Apache License 2.0 6 votes vote down vote up
/** 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);
        }
    }
}
 
Example 15
Source Project: wpcleaner   Source File: MWPaneSelectionManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 16
Source Project: netbeans   Source File: SearchCompletionItem.java    License: Apache License 2.0 6 votes vote down vote up
@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);
            }
        }
    });
}
 
Example 17
Source Project: netbeans   Source File: EditorContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
/** 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;
}
 
Example 18
Source Project: netbeans   Source File: WordCompletionItem.java    License: Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    });
}
 
Example 19
Source Project: netbeans   Source File: XMLDataObjectMimeTypeTest.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 20
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);
    }
}
 
Example 21
Source Project: netbeans   Source File: GuardedSectionsImpl.java    License: Apache License 2.0 6 votes vote down vote up
/** 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);
        }
    }
}
 
Example 22
Source Project: otroslogviewer   Source File: FormatMessageDialogWorker.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 23
Source Project: netbeans   Source File: DumpTokens.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 24
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);
		}
	}
 
Example 25
Source Project: netbeans   Source File: ComputeAnnotations.java    License: Apache License 2.0 5 votes vote down vote up
@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});
}
 
Example 26
Source Project: netbeans   Source File: PropertiesEditorSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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()));
        }
    }
}
 
Example 27
Source Project: netbeans   Source File: AnnotationView.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 28
Source Project: SikuliX1   Source File: PythonIndentation.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 29
Source Project: dsworkbench   Source File: AttackCalculationPanel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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");
}
 
Example 30
Source Project: FancyBing   Source File: GuiUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
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);
}