下面列出了怎么用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();
}
/**
* 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();
}
}
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();
}
/**
* @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;
}
@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);
}
/**
* @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;
}
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;
}
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;
}
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();
}
});
}
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;
}
}
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);
}
}
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");
}
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");
}
/**
* 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);
}
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);
}
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;
}
}
}
});
}
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 "";
}
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);
}
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);
}
@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());
}
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);
}
}
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));
}
}
public MatchingHighlighter(SmartDocumentFilter smartDocumentFilter, JTextPane textEditor) {
this.smartDocumentFilter = smartDocumentFilter;
this.textEditor = textEditor;
this.doc = (DefaultStyledDocument) textEditor.getStyledDocument();
initStyles();
}
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();
}