Java Code Examples for javax.swing.text.DefaultStyledDocument

The following examples show how to use javax.swing.text.DefaultStyledDocument. 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
/**
 * 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();
}
 
Example 2
/**
 * 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();
}
 
Example 3
Source Project: gate-core   Source File: LogArea.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
/**
 * {@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();
	}
}
 
Example 5
Source Project: groovy   Source File: ConsoleTextEditor.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 6
/**
 * 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();
}
 
Example 7
/**
 * 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();
}
 
Example 8
Source Project: bither-desktop-java   Source File: TextBoxes.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example 9
Source Project: android-classyshark   Source File: DisplayArea.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 10
Source Project: bither-desktop-java   Source File: TextBoxes.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example 11
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 12
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;
}
 
Example 13
Source Project: netbeans   Source File: HighlightingTest.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 14
Source Project: netbeans   Source File: HintsControllerImplTest.java    License: Apache License 2.0 5 votes vote down vote up
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();
        }
    });
}
 
Example 15
Source Project: netbeans   Source File: SyntaxHighlightingTest.java    License: Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example 16
Source Project: netbeans   Source File: SourceTest.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 17
Source Project: netbeans   Source File: CodeGenerationTest.java    License: Apache License 2.0 5 votes vote down vote up
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");
}
 
Example 18
Source Project: netbeans   Source File: CodeGenerationTest.java    License: Apache License 2.0 5 votes vote down vote up
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");
}
 
Example 19
Source Project: freecol   Source File: Utility.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 20
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);
}
 
Example 21
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);
}
 
Example 22
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;
				}
			}
		}
	});

}
 
Example 23
Source Project: binnavi   Source File: BaseTypeTableCellRenderer.java    License: Apache License 2.0 5 votes vote down vote up
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 "";
}
 
Example 24
Source Project: binnavi   Source File: BaseTypeTableCellRenderer.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 25
Source Project: binnavi   Source File: BaseTypeTableCellRenderer.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 26
Source Project: triplea   Source File: ChatPanelTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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());
}
 
Example 27
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 28
Source Project: groovy   Source File: TextEditor.java    License: Apache License 2.0 5 votes vote down vote up
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));
    }
}
 
Example 29
Source Project: groovy   Source File: MatchingHighlighter.java    License: Apache License 2.0 5 votes vote down vote up
public MatchingHighlighter(SmartDocumentFilter smartDocumentFilter, JTextPane textEditor) {
    this.smartDocumentFilter = smartDocumentFilter;
    this.textEditor = textEditor;
    this.doc = (DefaultStyledDocument) textEditor.getStyledDocument();

    initStyles();
}
 
Example 30
Source Project: groovy   Source File: SmartDocumentFilter.java    License: Apache License 2.0 5 votes vote down vote up
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();
}