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

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

/**
 * This highlights the text within the specified range
 *
 * @param startingIndex where to start the highlight
 * @param endingIndex where to end the highlight
 * @param ensureVisible true to scroll to the text
 * @param isEmphasized true to use an emphasized highlight (versus a regular highlight). Useful for showing the 'current' highlighted result.
 */
public void highlightText(int startingIndex, int endingIndex, boolean ensureVisible, boolean isEmphasized) {
    int length = endingIndex - startingIndex;

    AttributeSet style;
    if (isEmphasized) {
        style = emphasizedHighlightStyle;
    } else {
        style = highlightStyle;
    }

    ((DefaultStyledDocument) textComponentToSearch.getDocument()).setCharacterAttributes(startingIndex, length, style, true);

    if (ensureVisible) {
        Utility.scrollToText(textComponentToSearch, startingIndex, endingIndex);
        textComponentToSearch.setCaretPosition(endingIndex);
    }

    textComponentToSearch.repaint();
}
 
/**
 * This highlights the text within the specified range
 *
 * @param startingIndex where to start the highlight
 * @param endingIndex where to end the highlight
 * @param ensureVisible true to scroll to the text
 * @param isEmphasized true to use an emphasized highlight (versus a regular highlight). Useful for showing the 'current' highlighted result.
 */
public void highlightText(int startingIndex, int endingIndex, boolean ensureVisible, boolean isEmphasized) {
    int length = endingIndex - startingIndex;

    AttributeSet style;
    if (isEmphasized) {
        style = emphasizedHighlightStyle;
    } else {
        style = highlightStyle;
    }

    ((DefaultStyledDocument) textComponentToSearch.getDocument()).setCharacterAttributes(startingIndex, length, style, true);

    if (ensureVisible) {
        Utility.scrollToText(textComponentToSearch, startingIndex, endingIndex);
        textComponentToSearch.setCaretPosition(endingIndex);
    }

    textComponentToSearch.repaint();
}
 
源代码3 项目: gate-core   文件: LogArea.java
/**
 * Try and recover from a BadLocationException thrown when inserting a string
 * into the log area. This method must only be called on the AWT event
 * handling thread.
 */
private void handleBadLocationException(BadLocationException e,
    String textToInsert, Style style) {
  originalErr.println("BadLocationException encountered when writing to "
      + "the log area: " + e);
  originalErr.println("trying to recover...");

  Document newDocument = new DefaultStyledDocument();
  try {
    StringBuilder sb = new StringBuilder();
    sb.append("An error occurred when trying to write a message to the log area.  The log\n");
    sb.append("has been cleared to try and recover from this problem.\n\n");
    sb.append(textToInsert);

    newDocument.insertString(0, sb.toString(), style);
  } catch(BadLocationException e2) {
    // oh dear, all bets are off now...
    e2.printStackTrace(originalErr);
    return;
  }
  // replace the log area's document with the new one
  setDocument(newDocument);
}
 
/**
 * {@inheritDoc}
 */
public String extractText(InputStream stream, String type, String encoding) throws IOException {

	try {
		RTFEditorKit rek = new RTFEditorKit();
		DefaultStyledDocument doc = new DefaultStyledDocument();
		rek.read(stream, doc, 0);
		String text = doc.getText(0, doc.getLength());
		return text;
	} catch (Throwable e) {
		logger.warn("Failed to extract RTF text content", e);
		throw new IOException(e.getMessage(), e);
	} finally {
		stream.close();
	}
}
 
源代码5 项目: groovy   文件: ConsoleTextEditor.java
public void enableHighLighter(Class clazz) {
    DefaultStyledDocument doc = (DefaultStyledDocument) textEditor.getDocument();

    try {
        DocumentFilter documentFilter = (DocumentFilter) clazz.getConstructor(doc.getClass()).newInstance(doc);
        doc.setDocumentFilter(documentFilter);

        disableMatchingHighlighter();
        if (documentFilter instanceof SmartDocumentFilter) {
            final SmartDocumentFilter smartDocumentFilter = (SmartDocumentFilter) documentFilter;
            enableMatchingHighlighter(smartDocumentFilter);
        }
    } catch (ReflectiveOperationException e) {
        e.printStackTrace();
    }
}
 
/**
 * This highlights the text within the specified range
 *
 * @param startingIndex where to start the highlight
 * @param endingIndex where to end the highlight
 * @param ensureVisible true to scroll to the text
 * @param isEmphasized true to use an emphasized highlight (versus a regular highlight). Useful for showing the 'current' highlighted result.
 */
public void highlightText(int startingIndex, int endingIndex, boolean ensureVisible, boolean isEmphasized) {
    int length = endingIndex - startingIndex;

    AttributeSet style;
    if (isEmphasized) {
        style = emphasizedHighlightStyle;
    } else {
        style = highlightStyle;
    }

    ((DefaultStyledDocument) textComponentToSearch.getDocument()).setCharacterAttributes(startingIndex, length, style, true);

    if (ensureVisible) {
        Utility.scrollToText(textComponentToSearch, startingIndex, endingIndex);
        textComponentToSearch.setCaretPosition(endingIndex);
    }

    textComponentToSearch.repaint();
}
 
/**
 * This highlights the text within the specified range
 *
 * @param startingIndex where to start the highlight
 * @param endingIndex where to end the highlight
 * @param ensureVisible true to scroll to the text
 * @param isEmphasized true to use an emphasized highlight (versus a regular highlight). Useful for showing the 'current' highlighted result.
 */
public void highlightText(int startingIndex, int endingIndex, boolean ensureVisible, boolean isEmphasized) {
    int length = endingIndex - startingIndex;

    AttributeSet style;
    if (isEmphasized) {
        style = emphasizedHighlightStyle;
    } else {
        style = highlightStyle;
    }

    ((DefaultStyledDocument) textComponentToSearch.getDocument()).setCharacterAttributes(startingIndex, length, style, true);

    if (ensureVisible) {
        Utility.scrollToText(textComponentToSearch, startingIndex, endingIndex);
        textComponentToSearch.setCaretPosition(endingIndex);
    }

    textComponentToSearch.repaint();
}
 
源代码8 项目: bither-desktop-java   文件: TextBoxes.java
/**
 * @return A new "Password" text field
 */
public static JPasswordField newPassword() {

    JPasswordField passwordField = new JPasswordField(BitherUI.PASSWORD_LENGTH);

    // Ensure it is accessible
    AccessibilityDecorator.apply(passwordField, MessageKey.ENTER_PASSWORD);

    // Provide a consistent echo character across all components
    passwordField.setEchoChar(getPasswordEchoChar());

    // Limit the length of the underlying document
    DefaultStyledDocument doc = new DefaultStyledDocument();
    doc.setDocumentFilter(new DocumentMaxLengthFilter(BitherUI.PASSWORD_LENGTH));
    passwordField.setDocument(doc);

    // Set the theme
    passwordField.setBorder(new TextBubbleBorder(Themes.currentTheme.dataEntryBorder()));
    passwordField.setBackground(Themes.currentTheme.dataEntryBackground());

    passwordField.setOpaque(false);

    return passwordField;
}
 
源代码9 项目: android-classyshark   文件: DisplayArea.java
@Override
public void displayClass(List<Translator.ELEMENT> elements, String key) {
    displayDataState = DisplayDataState.INSIDE_CLASS;
    clearText();
    StyleConstants.setFontSize(style,  20);
    StyleConstants.setBackground(style, theme.getBackgroundColor());

    Document doc = new DefaultStyledDocument();

    fillTokensToDoc(elements, doc, false);

    StyleConstants.setForeground(style, theme.getIdentifiersColor());

    jTextPane.setDocument(doc);

    int i = calcScrollingPosition(key);
    jTextPane.setCaretPosition(i);
}
 
源代码10 项目: bither-desktop-java   文件: TextBoxes.java
/**
 * @return A new "Password" text field
 */
public static JPasswordField newPassword() {

    JPasswordField passwordField = new JPasswordField(BitherUI.PASSWORD_LENGTH);

    // Ensure it is accessible
    AccessibilityDecorator.apply(passwordField, MessageKey.ENTER_PASSWORD);

    // Provide a consistent echo character across all components
    passwordField.setEchoChar(getPasswordEchoChar());

    // Limit the length of the underlying document
    DefaultStyledDocument doc = new DefaultStyledDocument();
    doc.setDocumentFilter(new DocumentMaxLengthFilter(BitherUI.PASSWORD_LENGTH));
    passwordField.setDocument(doc);

    // Set the theme
    passwordField.setBorder(new TextBubbleBorder(Themes.currentTheme.dataEntryBorder()));
    passwordField.setBackground(Themes.currentTheme.dataEntryBackground());

    passwordField.setOpaque(false);

    return passwordField;
}
 
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;
}
 
源代码12 项目: document-management-software   文件: RTFParser.java
protected String extractText(InputStream input) throws IOException, BadLocationException {
	RTFEditorKit rek = new RTFEditorKit();
	DefaultStyledDocument doc = new DefaultStyledDocument();
	rek.read(input, doc, 0);
	String text = doc.getText(0, doc.getLength());
	return text;
}
 
源代码13 项目: netbeans   文件: HighlightingTest.java
private Document createDocument(String text) {
    try {
        DefaultStyledDocument doc = new DefaultStyledDocument();
        doc.putProperty(Language.class, JavaTokenId.language());
        doc.insertString(0, text, SimpleAttributeSet.EMPTY);
        return doc;
    } catch (BadLocationException e) {
        fail(e.getMessage());
    }
    return null;
}
 
源代码14 项目: netbeans   文件: HintsControllerImplTest.java
public void testComputeLineSpan() throws Exception {
    doTestComputeLineSpan(new DocumentCreator() {
        public Document createDocument() {
            return new NbEditorDocument(BaseKit.class);
        }
    });
    doTestComputeLineSpan(new DocumentCreator() {
        public Document createDocument() {
            return new DefaultStyledDocument();
        }
    });
}
 
源代码15 项目: netbeans   文件: SyntaxHighlightingTest.java
private Document createDocument(Language lang, String text) {
    try {
        DefaultStyledDocument doc = new DefaultStyledDocument();
        doc.putProperty(Language.class, lang);
        doc.insertString(0, text, SimpleAttributeSet.EMPTY);
        return doc;
    } catch (BadLocationException e) {
        fail(e.getMessage());
        return null;
    }
}
 
源代码16 项目: netbeans   文件: SourceTest.java
private Document createDocument(String mimeType, String contents) {
    Document doc = new DefaultStyledDocument();
    doc.putProperty("mimeType", mimeType);
    try {
        doc.insertString(0, contents, null);
        return doc;
    } catch (BadLocationException ble) {
        throw new IllegalStateException(ble);
    }
}
 
源代码17 项目: netbeans   文件: CodeGenerationTest.java
public void testSimpleCodeGenerator() {
    Document doc = new DefaultStyledDocument();
    doc.putProperty(NbEditorDocument.MIME_TYPE_PROP, "text/x-simple-codegen-test");
    String[] generatorNames = NbGenerateCodeAction.test(doc, 0);
    assertEquals(generatorNames.length, 1);
    assertEquals(generatorNames[0], "SimpleCodeGenerator");
}
 
源代码18 项目: netbeans   文件: CodeGenerationTest.java
public void testCodeGenerator() {
    Document doc = new DefaultStyledDocument();
    doc.putProperty(NbEditorDocument.MIME_TYPE_PROP, "text/x-codegen-test");
    String[] generatorNames = NbGenerateCodeAction.test(doc, 0);
    assertEquals(generatorNames.length, 1);
    assertEquals(generatorNames[0], "CodeGenerator");
}
 
源代码19 项目: freecol   文件: Utility.java
/**
 * Get a {@code JTextPane} with default styles.
 *
 * @return The default {@code JTextPane} to use.
 */
public static JTextPane getDefaultTextPane() {
    DefaultStyledDocument document
        = new DefaultStyledDocument(STYLE_CONTEXT);

    JTextPane textPane = new JTextPane(document);
    textPane.setOpaque(false);
    textPane.setEditable(false);
    textPane.setLogicalStyle(STYLE_CONTEXT.getStyle("regular"));
    return textPane;
}
 
static void createStyles() {
    styles = new StyleContext();
    doc = new DefaultStyledDocument(styles);
    contentAttributes = new HashMap<>();

    // no attributes defined
    Style s = styles.addStyle(null, null);
    contentAttributes.put("none", s);

    Style def = styles.getStyle(StyleContext.DEFAULT_STYLE);

    Style heading = styles.addStyle("heading", def);
    StyleConstants.setFontFamily(heading, "SansSerif");
    StyleConstants.setBold(heading, true);
    StyleConstants.setAlignment(heading, StyleConstants.ALIGN_CENTER);
    StyleConstants.setSpaceAbove(heading, 10);
    StyleConstants.setSpaceBelow(heading, 10);
    StyleConstants.setFontSize(heading, 18);

    // Title
    Style sty = styles.addStyle("title", heading);
    StyleConstants.setFontSize(sty, 32);

    // author
    sty = styles.addStyle("author", heading);
    StyleConstants.setItalic(sty, true);
    StyleConstants.setSpaceBelow(sty, 25);
}
 
源代码21 项目: jdk8u_jdk   文件: JViewPortBackingStoreImageTest.java
static void createStyles() {
    styles = new StyleContext();
    doc = new DefaultStyledDocument(styles);
    contentAttributes = new HashMap<>();

    // no attributes defined
    Style s = styles.addStyle(null, null);
    contentAttributes.put("none", s);

    Style def = styles.getStyle(StyleContext.DEFAULT_STYLE);

    Style heading = styles.addStyle("heading", def);
    StyleConstants.setFontFamily(heading, "SansSerif");
    StyleConstants.setBold(heading, true);
    StyleConstants.setAlignment(heading, StyleConstants.ALIGN_CENTER);
    StyleConstants.setSpaceAbove(heading, 10);
    StyleConstants.setSpaceBelow(heading, 10);
    StyleConstants.setFontSize(heading, 18);

    // Title
    Style sty = styles.addStyle("title", heading);
    StyleConstants.setFontSize(sty, 32);

    // author
    sty = styles.addStyle("author", heading);
    StyleConstants.setItalic(sty, true);
    StyleConstants.setSpaceBelow(sty, 25);
}
 
源代码22 项目: rapidminer-studio   文件: ColoredJTextPane.java
public ColoredJTextPane() {
	super();
	setDocument(new DefaultStyledDocument() {

		private static final long serialVersionUID = 1L;

		@Override
		public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
			super.insertString(offs, str, a);

			// now color all texts again
			// do coloring of words but ignore keys unless it is word termination
			String text = getText(0, getLength());
			char[] chars = text.toCharArray();
			StyleContext context = StyleContext.getDefaultStyleContext();
			int lastStart = 0;
			boolean charactersSinceLastStart = false;
			for (int i = 0; i < text.length(); i++) {
				if (!Character.isLetter(chars[i])) {
					if (charactersSinceLastStart) {
						AttributeSet attributeSet = context.addAttribute(SimpleAttributeSet.EMPTY,
								StyleConstants.Foreground, getColor(new String(chars, lastStart, i - lastStart)));
						setCharacterAttributes(lastStart, i - lastStart, attributeSet, true);
					}
					lastStart = i + 1;
					charactersSinceLastStart = false;
				} else {
					charactersSinceLastStart = true;
				}
			}
		}
	});

}
 
源代码23 项目: 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 "";
}
 
源代码24 项目: binnavi   文件: BaseTypeTableCellRenderer.java
public static FormattedCharacterBuffer renderType(final TypeInstance instance, Font font,
    int desiredWidth, final boolean renderData) {
  DefaultStyledDocument document = new DefaultStyledDocument();

  generateDocument(instance, renderData, document);
  return convertDocumentToFormattedCharacterBuffer(document, font, desiredWidth);
}
 
源代码25 项目: binnavi   文件: BaseTypeTableCellRenderer.java
public static FormattedCharacterBuffer renderTypeLine(final TypeInstance instance,
    Font font, int desiredWidth, final boolean renderData, final int line) {
  DefaultStyledDocument document = new DefaultStyledDocument();

  generateDocument(instance, renderData, document);
  return convertDocumentToFormattedCharacterBuffer(document, font, desiredWidth);
}
 
源代码26 项目: triplea   文件: ChatPanelTest.java
@Test
void testTrim() throws Exception {
  final StyledDocument doc = new DefaultStyledDocument();
  doc.insertString(0, "\n".repeat(10), null);
  ChatMessagePanel.trimLines(doc, 20);
  assertEquals(10, doc.getLength());
  ChatMessagePanel.trimLines(doc, 10);
  assertEquals(10, doc.getLength());
  ChatMessagePanel.trimLines(doc, 5);
  assertEquals(5, doc.getLength());
  ChatMessagePanel.trimLines(doc, 1);
  assertEquals(1, doc.getLength());
}
 
源代码27 项目: 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);
		}
	}
 
源代码28 项目: groovy   文件: TextEditor.java
private void setRenderRange(int start, int stop) {
    DocumentFilter documentFilter = ((DefaultStyledDocument) TextEditor.this.getDocument()).getDocumentFilter();
    if (documentFilter instanceof SmartDocumentFilter) {
        SmartDocumentFilter smartDocumentFilter = (SmartDocumentFilter) documentFilter;
        smartDocumentFilter.setRenderRange(Tuple.tuple(start, stop));
    }
}
 
源代码29 项目: groovy   文件: MatchingHighlighter.java
public MatchingHighlighter(SmartDocumentFilter smartDocumentFilter, JTextPane textEditor) {
    this.smartDocumentFilter = smartDocumentFilter;
    this.textEditor = textEditor;
    this.doc = (DefaultStyledDocument) textEditor.getStyledDocument();

    initStyles();
}
 
源代码30 项目: groovy   文件: SmartDocumentFilter.java
public SmartDocumentFilter(DefaultStyledDocument styledDocument) {
    this.styledDocument = styledDocument;

    this.styleContext = StyleContext.getDefaultStyleContext();
    this.defaultStyle = this.styleContext.getStyle(StyleContext.DEFAULT_STYLE);
    StyleConstants.setFontFamily(this.defaultStyle, MONOSPACED);

    initStyles();
}
 
 类所在包
 类方法
 同包方法