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

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

源代码1 项目: org.alloytools.alloy   文件: SwingLogPanel.java
/** Set the font name. */
public void setFontName(String fontName) {
    if (log == null)
        return;
    this.fontName = fontName;
    log.setFont(new Font(fontName, Font.PLAIN, fontSize));
    StyleConstants.setFontFamily(styleRegular, fontName);
    StyleConstants.setFontFamily(styleBold, fontName);
    StyleConstants.setFontFamily(styleRed, fontName);
    StyleConstants.setFontSize(styleRegular, fontSize);
    StyleConstants.setFontSize(styleBold, fontSize);
    StyleConstants.setFontSize(styleRed, fontSize);
    // Changes all existing text
    StyledDocument doc = log.getStyledDocument();
    Style temp = doc.addStyle("temp", null);
    StyleConstants.setFontFamily(temp, fontName);
    StyleConstants.setFontSize(temp, fontSize);
    doc.setCharacterAttributes(0, doc.getLength(), temp, false);
    // Changes all existing hyperlinks
    Font newFont = new Font(fontName, Font.BOLD, fontSize);
    for (JLabel link : links) {
        link.setFont(newFont);
    }
}
 
源代码2 项目: 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;
  }
}
 
源代码3 项目: wpcleaner   文件: MWPaneFormatter.java
/**
 * Format elements in a MediaWikiPane highlighting non wiki text.
 * 
 * @param doc Document to be formatted.
 * @param analysis Page analysis.
 */
private void formatWikiText(
    StyledDocument doc,
    PageAnalysis analysis) {
  if ((doc == null) || (analysis == null)) {
    return;
  }
  Style style = doc.getStyle(ConfigurationValueStyle.COMMENTS.getName());
  List<Area> areas = analysis.getAreas().getAreas();
  if (areas != null) {
    for (Area area : areas) {
      int beginIndex = area.getBeginIndex();
      int endIndex = area.getEndIndex();
      doc.setCharacterAttributes(
          beginIndex, endIndex - beginIndex,
          style, true);
    }
  }
}
 
源代码4 项目: consulo   文件: Browser.java
private void setupStyle() {
  Document document = myHTMLViewer.getDocument();
  if (!(document instanceof StyledDocument)) {
    return;
  }

  StyledDocument styledDocument = (StyledDocument)document;

  EditorColorsManager colorsManager = EditorColorsManager.getInstance();
  EditorColorsScheme scheme = colorsManager.getGlobalScheme();

  Style style = styledDocument.addStyle("active", null);
  StyleConstants.setFontFamily(style, scheme.getEditorFontName());
  StyleConstants.setFontSize(style, scheme.getEditorFontSize());
  styledDocument.setCharacterAttributes(0, document.getLength(), style, false);
}
 
源代码5 项目: FancyBing   文件: GuiUtil.java
public static void setStyle(JTextPane textPane, int start, int length,
                            String name)
{
    StyledDocument doc = textPane.getStyledDocument();
    Style style;
    if (name == null)
    {
        StyleContext context = StyleContext.getDefaultStyleContext();
        style = context.getStyle(StyleContext.DEFAULT_STYLE);
    }
    else
        style = doc.getStyle(name);
    doc.setCharacterAttributes(start, length, style, true);
}
 
源代码6 项目: tracker   文件: ParticleDataTrackFunctionPanel.java
@Override
protected void refreshInstructions(FunctionEditor source, boolean editing, int selectedColumn) {
  StyledDocument doc = instructions.getStyledDocument();
  Style style = doc.getStyle("blue");                                                //$NON-NLS-1$
  String s = TrackerRes.getString("ParticleDataTrackFunctionPanel.Instructions.General"); //$NON-NLS-1$
  if(!editing && hasInvalidExpressions()) {                            // error condition
    s = ToolsRes.getString("FunctionPanel.Instructions.BadCell");           //$NON-NLS-1$
    style = doc.getStyle("red");                                            //$NON-NLS-1$
  }
  instructions.setText(s);
  int len = instructions.getText().length();
  doc.setCharacterAttributes(0, len, style, false);
  revalidate();
}
 
源代码7 项目: netbeans   文件: VCSHyperlinkSupport.java
@Override
public void insertString(StyledDocument sd, Style style) throws BadLocationException {
    sd.insertString(sd.getLength(), text, style);
    for (int i = 0; i < length; i++) {
        sd.setCharacterAttributes(sd.getLength() - text.length() + start[i], end[i] - start[i], issueHyperlinkStyle, false);
    }
}
 
源代码8 项目: ramus   文件: TextPanelWithLinksDetector.java
private void applyLinkStyles() {
    Map<Integer, String> links = getLinks();
    if (links.equals(this.links)) {
        return;
    }
    this.links.clear();
    this.links.putAll(links);
    StyledDocument kit = (StyledDocument) this.getDocument();
    kit.setCharacterAttributes(0, getText().length(), new SimpleAttributeSet(), true);
    for (Map.Entry<Integer, String> entry : links.entrySet()) {
        kit.setCharacterAttributes(entry.getKey(), entry.getValue().length(), this.linkStyle, true);
    }
}
 
源代码9 项目: pumpernickel   文件: TextComponentHighlighter.java
/**
 * This reapplies highlights and AttributeSets to this text component.
 * 
 * @param text
 *            the text to format.
 * @param selectionStart
 *            the current selection start.
 * @param selectionEnd
 *            the current selection end.
 */
protected void rehighlightText(final String text, final int selectionStart,
		final int selectionEnd, boolean invokeLater) {
	for (Object oldHighlight : allHighlights) {
		jtc.getHighlighter().removeHighlight(oldHighlight);
	}
	allHighlights.clear();

	Runnable changeStylesRunnable = new Runnable() {
		public void run() {
			removeDocumentListeners();
			try {
				Document doc = jtc.getDocument();
				if (!(doc instanceof StyledDocument)) {
					printOnce("TextComponentHighlighter: Attributes were provided but the document does not support styled attributes.");
					return;
				}
				SimpleAttributeSet defaultAttributes = getDefaultAttributes();

				StyledDocument d = (StyledDocument) doc;
				d.setCharacterAttributes(0, d.getLength(),
						defaultAttributes, true);
				if (active) {
					formatTextComponent(text, d, selectionStart,
							selectionEnd);
				}
			} catch (BadLocationException e) {
				throw new RuntimeException(e);
			} finally {
				addDocumentListeners();
			}
		}
	};
	if (invokeLater) {
		SwingUtilities.invokeLater(changeStylesRunnable);
	} else {
		changeStylesRunnable.run();
	}
}
 
源代码10 项目: Gaalop   文件: SourceFilePanel.java
void formatCode(String content) {
	try {
		StyledDocument doc = textPane.getStyledDocument();
		Matcher matcher = PATTERN.matcher(content);
		while (matcher.find()) {
			int start = matcher.start();
			int end = matcher.end();
			String keyword = matcher.group();
			doc.setCharacterAttributes(start, end-start, KEYWORDS.get(keyword), false);
		}
	} catch (Exception e) {
		System.err.println(e);
		textPane.setText(content);
	}
}
 
源代码11 项目: otroslogviewer   文件: FormatMessageDialogWorker.java
protected void updateChanges(List<TextChunkWithStyle> chunks) {
  LOGGER.trace("Start updating view with chunks, size: " + chunks.size());
  StyledDocument document = otrosJTextWithRulerScrollPane.getjTextComponent().getStyledDocument();
  int i = 0;
  for (TextChunkWithStyle chunk : chunks) {
    LOGGER.trace("Updating with chunk " + i++);
    try {

      if (chunk.getString() != null) {
        if (chunk.getMessageFragmentStyle() != null) {
          document.insertString(document.getLength(), chunk.getString(), chunk.getMessageFragmentStyle().getStyle());
        } else {
          document.insertString(document.getLength(), chunk.getString(), chunk.getStyle());
        }

      } else if (chunk.getMessageFragmentStyle() != null) {
        MessageFragmentStyle mfs = chunk.getMessageFragmentStyle();
        document.setCharacterAttributes(mfs.getOffset(), mfs.getLength(), mfs.getStyle(), mfs.isReplace());
      }
      if (chunk.getIcon() != null) {
        otrosJTextWithRulerScrollPane.getjTextComponent().insertIcon(chunk.getIcon());
      }
    } catch (BadLocationException e) {
      LOGGER.error("Can't update log details text area", e);
    }
  }

  otrosJTextWithRulerScrollPane.getjTextComponent().setCaretPosition(0);
  MessageUpdateUtils.highlightSearchResult(otrosJTextWithRulerScrollPane, colorizersContainer, otrosApplication.getTheme());
  RulerBarHelper.scrollToFirstMarker(otrosJTextWithRulerScrollPane);
}
 
源代码12 项目: wpcleaner   文件: HTMLPane.java
/**
 * Clear text.
 */
public void clearText() {
  Document doc = getDocument();
  if (doc != null) {
    if (doc instanceof StyledDocument) {
      StyledDocument styledDoc = (StyledDocument) doc;
      styledDoc.setCharacterAttributes(0, doc.getLength(), new SimpleAttributeSet(), true);
      styledDoc.setParagraphAttributes(0, doc.getLength(), new SimpleAttributeSet(), true);
    }
  }
  setText("");
}
 
源代码13 项目: trygve   文件: TextEditorGUI.java
public void setBreakpointToEOLAt(int byteOffset, int lineNumber) {
	final StyledDocument doc = (StyledDocument)editPane.getDocument();
	final Element paragraphElement = doc.getParagraphElement(byteOffset);
	if (paragraphElement.getClass() == BranchElement.class) {
		final SimpleAttributeSet sas = new SimpleAttributeSet(); 
		StyleConstants.setBackground(sas, Color.cyan);
		
		// Look for ending delimiter
		int length = 1;
		try {
			for (int i = byteOffset; ; i++) {
				if (i >= doc.getLength()) {
					length = i - byteOffset + 1;
					break;
				} else if (doc.getText(i, 1).equals("\n")) {
					length = i - byteOffset;
					break;
				}
			}
		} catch (BadLocationException ble) {
			length = 0;
		}
		if (0 < length) {
			doc.setCharacterAttributes(byteOffset, length, sas, false);
		}
	}
}
 
源代码14 项目: trygve   文件: TextEditorGUI.java
public void removeAllBreakpoints() {
	final StyledDocument doc = (StyledDocument)editPane.getDocument();
	final SimpleAttributeSet sas = new SimpleAttributeSet();
	StyleConstants.setBackground(sas, new java.awt.Color(233, 228, 242));
	
	// https://stackoverflow.com/questions/28927274/get-attributes-of-selected-text-in-jtextpane
	for(int i = 0; i < doc.getLength(); i++) {
	    final AttributeSet set = doc.getCharacterElement(i).getAttributes();
	    final Color backgroundColor = StyleConstants.getBackground(set);
	    if (backgroundColor.equals(Color.cyan)) {
	    	// The breakpoint color. Remove breakpoint annotation from this text
	    	doc.setCharacterAttributes(i, 1, sas, false);
	    }
	}
}
 
源代码15 项目: netbeans   文件: ShowGoldenFilesPanel.java
public void setDocument(StyledDocument doc, List<HighlightImpl> golden, List<HighlightImpl> test, File goldenFile, File testFile) {
    this.golden = golden;
    this.test = test;
    this.goldenFile = goldenFile;
    this.testFile = testFile;
    List<HighlightImpl> missing = new ArrayList<HighlightImpl>();
    List<HighlightImpl> added   = new ArrayList<HighlightImpl>();
    
    Map<String, HighlightImpl> name2Golden = new HashMap<String, HighlightImpl>();
    Map<String, HighlightImpl> name2Test   = new HashMap<String, HighlightImpl>();
    
    for (HighlightImpl g : golden) {
        name2Golden.put(g.getHighlightTestData(), g);
    }
    
    for (HighlightImpl t : test) {
        name2Test.put(t.getHighlightTestData(), t);
    }
    
    Set<String> missingNames = new HashSet<String>(name2Golden.keySet());
    
    missingNames.removeAll(name2Test.keySet());
    
    for (String m : missingNames) {
        missing.add(name2Golden.get(m));
    }
    
    Set<String> addedNames = new HashSet<String>(name2Test.keySet());
    
    addedNames.removeAll(name2Golden.keySet());
    
    for (String a : addedNames) {
        added.add(name2Test.get(a));
    }
    
    List<HighlightImpl> modified = new ArrayList<HighlightImpl>();
    
    modified.addAll(missing);
    modified.addAll(added);
    
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet as = sc.getEmptySet();
    
    as = sc.addAttribute(as, StyleConstants.Foreground, Color.RED);
    as = sc.addAttribute(as, StyleConstants.Bold, Boolean.TRUE);
    
    for (HighlightImpl h : modified) {
        doc.setCharacterAttributes(h.getStart(), h.getEnd() - h.getStart(), as, false);
    }
    
    jEditorPane1.setContentType("text/html");
    jEditorPane1.setDocument(doc);
}
 
源代码16 项目: osp   文件: FunctionEditor.java
public Component getTableCellEditorComponent(JTable atable, Object value, boolean isSelected, int row, int column) {
  table.rowToSelect = row;
  table.columnToSelect = column;
  if (usePopupEditor) {
  	undoEditsEnabled = false;
  	JDialog popup = getPopupEditor();
    if (functionPanel.functionTool!=null) {
    	// set font level of popup editor
   	int level = functionPanel.functionTool.getFontLevel();
   	FontSizer.setFonts(popup, level);
    }      	
    dragLabel.setText(ToolsRes.getString("FunctionEditor.DragLabel.Text")); //$NON-NLS-1$

   prevObject = objects.get(row);
   if (prevObject!=null) {
   	prevName = getName(prevObject);
   	prevExpression = getExpression(prevObject);
   }

    String val = value.toString();
    if (prevObject!=null && column>0) {
    	if (val.endsWith(DEGREES)) {
    		val = val.substring(0, val.length()-1);
    	}
    	else {
    		val = prevExpression;
    	}
    }
    
    popupField.setText(val);
   popupField.requestFocusInWindow();
	try {
	String s = popupField.getText();
	setInitialValue(s);
} catch (NumberFormatException ex) {
}

   popupField.selectAll();
   popupField.setBackground(Color.WHITE);
   if (column==1) {
    variablesPane.setText(getVariablesString(":\n")); //$NON-NLS-1$
     StyledDocument doc = variablesPane.getStyledDocument();
     Style blue = doc.getStyle("blue"); //$NON-NLS-1$
     doc.setCharacterAttributes(0, variablesPane.getText().length(), blue, false);
     popup.getContentPane().add(variablesPane, BorderLayout.CENTER);
   }
   else {
     popup.getContentPane().remove(variablesPane);
   }
   Rectangle cell = table.getCellRect(row, column, true);
   minPopupWidth = cell.width+2;
   Dimension dim = resizePopupEditor();
   Point p = table.getLocationOnScreen();
   popup.setLocation(p.x+cell.x+cell.width/2-dim.width/2, 
   		p.y+cell.y+cell.height/2-dim.height/2);
   popup.setVisible(true);
  }
  else {
  	field.setText(value.toString());
    functionPanel.refreshInstructions(FunctionEditor.this, true, column);
    functionPanel.tableEditorField = field;
  }
  return panel;
}
 
源代码17 项目: netbeans   文件: SummaryCellRenderer.java
private void addAuthor (JTextPane pane, RevisionItem item, boolean selected, Collection<SearchHighlight> highlights) throws BadLocationException {
    LogEntry entry = item.getUserData();
    StyledDocument sd = pane.getStyledDocument();
    clearSD(pane, sd);
    Style selectedStyle = createSelectedStyle(pane);
    Style normalStyle = createNormalStyle(pane);
    Style style;
    if (selected) {
        style = selectedStyle;
    } else {
        style = normalStyle;
    }
    Style authorStyle = createAuthorStyle(pane, normalStyle);
    Style hiliteStyle = createHiliteStyleStyle(pane, normalStyle, searchHiliteAttrs);
    String author = entry.getAuthor();
    AuthorLinker l = linkerSupport.getLinker(VCSHyperlinkSupport.AuthorLinker.class, id);
    if(l == null) {
        VCSKenaiAccessor.KenaiUser kenaiUser = getKenaiUser(author);
        if (kenaiUser != null) {
            l = new VCSHyperlinkSupport.AuthorLinker(kenaiUser, authorStyle, sd, author);
            linkerSupport.add(l, id);
        }
    }
    int pos = sd.getLength();
    if(l != null) {
        l.insertString(sd, selected ? style : null);
    } else {
        sd.insertString(sd.getLength(), author, style);
    }
    if (!selected) {
        for (SearchHighlight highlight : highlights) {
            if (highlight.getKind() == SearchHighlight.Kind.AUTHOR) {
                int doclen = sd.getLength();
                String highlightMessage = highlight.getSearchText();
                String authorText = sd.getText(pos, doclen - pos).toLowerCase();
                int idx = authorText.indexOf(highlightMessage);
                if (idx > -1) {
                    sd.setCharacterAttributes(doclen - authorText.length() + idx, highlightMessage.length(), hiliteStyle, false);
                }
            }
        }
    }
}
 
源代码18 项目: uima-uimaj   文件: CasAnnotationViewer.java
/**
 * Do bold face by key words.
 */
private void doBoldFaceByKeyWords() {
  if (this.boldFaceKeyWords == null || this.boldFaceKeyWords.length == 0) {
    return;
  }

  // build regular expression
  StringBuffer regex = new StringBuffer();
  for (int i = 0; i < this.boldFaceKeyWords.length; i++) {
    if (i > 0) {
      regex.append('|');
    }
    regex.append("\\b");
    String keyWord = this.boldFaceKeyWords[i];
    for (int j = 0; j < keyWord.length(); j++) {
      char c = keyWord.charAt(j);
      if (Character.isLetter(c)) {
        regex.append('[').append(Character.toLowerCase(c)).append(Character.toUpperCase(c)).append(']');
      } else if (c == '.' || c == '^' || c == '&' || c == '\\' || c == '(' || c == ')') {
        regex.append('\\').append(c);
      } else {
        regex.append(c);
      }
    }
    regex.append("\\b");
  }
  Pattern pattern = Pattern.compile(regex.toString());
  Matcher matcher = pattern.matcher(this.cas.getDocumentText());
  // match
  int pos = 0;
  while (matcher.find(pos)) {
    int begin = matcher.start();
    int end = matcher.end();
    MutableAttributeSet attrs = new SimpleAttributeSet();
    StyleConstants.setBold(attrs, true);
    StyledDocument doc = (StyledDocument) this.textPane.getDocument();
    doc.setCharacterAttributes(begin, end - begin, attrs, false);
    if (pos == end) { // infinite loop check
      break;
    }
    pos = end;
  }
}
 
源代码19 项目: wpcleaner   文件: MWPaneCheckWikiFormatter.java
/**
 * Format a Check Wiki error in a MediaWikiPane.
 * 
 * @param doc Document to be formatted.
 * @param error Check Wiki error to be formatted.
 */
private void formatCheckWikiError(
    StyledDocument doc,
    CheckErrorResult error) {

  // Basic verifications
  if ((doc == null) || (error == null)) {
    return;
  }

  // Format error
  ConfigurationValueStyle styleConfig = ConfigurationValueStyle.CHECK_WIKI_ERROR;
  if (error.getErrorLevel() == CheckErrorResult.ErrorLevel.CORRECT) {
    styleConfig = ConfigurationValueStyle.CHECK_WIKI_OK;
  } else if (error.getErrorLevel() == CheckErrorResult.ErrorLevel.WARNING) {
    styleConfig = ConfigurationValueStyle.CHECK_WIKI_WARNING;
  }
  doc.setCharacterAttributes(
      error.getStartPosition(),
      error.getLength(),
      doc.getStyle(styleConfig.getName()),
      true);
  SimpleAttributeSet attributes = new SimpleAttributeSet();
  attributes.addAttribute(MWPaneFormatter.ATTRIBUTE_INFO, error);
  attributes.addAttribute(MWPaneFormatter.ATTRIBUTE_UUID, UUID.randomUUID());
  doc.setCharacterAttributes(
      error.getStartPosition(),
      error.getLength(),
      attributes, false);

  // Manage position
  if (error.getErrorLevel() == CheckErrorResult.ErrorLevel.CORRECT) {
    if (error.getStartPosition() < thirdStartPosition) {
      thirdStartPosition = error.getStartPosition();
      thirdEndPosition = error.getEndPosition();
    }
  } else if (error.getErrorLevel() == CheckErrorResult.ErrorLevel.WARNING) {
    if (error.getStartPosition() < secondStartPosition) {
      secondStartPosition = error.getStartPosition();
      secondEndPosition = error.getEndPosition();
    }
  } else {
    if (error.getStartPosition() < startPosition) {
      startPosition = error.getStartPosition();
      endPosition = error.getEndPosition();
    }
  }
}
 
源代码20 项目: java-swing-tips   文件: MainPanel.java
private MainPanel() {
  super(new BorderLayout());
  textArea.setEditable(false);

  StyleContext style = new StyleContext();
  StyledDocument doc = new DefaultStyledDocument(style);
  try {
    doc.insertString(0, TEXT + "\n" + TEXT, null);
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
  MutableAttributeSet attr1 = new SimpleAttributeSet();
  attr1.addAttribute(StyleConstants.Bold, Boolean.TRUE);
  attr1.addAttribute(StyleConstants.Foreground, Color.RED);
  doc.setCharacterAttributes(4, 11, attr1, false);

  MutableAttributeSet attr2 = new SimpleAttributeSet();
  attr2.addAttribute(StyleConstants.Underline, Boolean.TRUE);
  doc.setCharacterAttributes(10, 20, attr2, false);

  JTextPane textPane = new JTextPane(doc);
  textPane.addCaretListener(e -> {
    if (e.getDot() == e.getMark()) {
      AttributeSet a = doc.getCharacterElement(e.getDot()).getAttributes();
      append("isBold: " + StyleConstants.isBold(a));
      append("isUnderline: " + StyleConstants.isUnderline(a));
      append("Foreground: " + StyleConstants.getForeground(a));
      append("FontFamily: " + StyleConstants.getFontFamily(a));
      append("FontSize: " + StyleConstants.getFontSize(a));
      append("Font: " + style.getFont(a));
      append("----");
    }
  });

  JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
  sp.setResizeWeight(.5);
  sp.setTopComponent(new JScrollPane(textPane));
  sp.setBottomComponent(new JScrollPane(textArea));
  add(sp);
  setPreferredSize(new Dimension(320, 240));
}