/** * 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); }
private JTextPane getCodeArea(){ final StyleContext sc = new StyleContext(); final DefaultStyledDocument doc = new DefaultStyledDocument(sc); final JTextPane codeArea = new JTextPane(doc); codeArea.setBackground(new Color(0x25401C)); codeArea.setCaretColor(new Color(0xD1E8CE)); final Style bodyStyle = sc.addStyle("body", null); bodyStyle.addAttribute(StyleConstants.Foreground, new Color(0x789C6C)); bodyStyle.addAttribute(StyleConstants.FontSize, 13); bodyStyle.addAttribute(StyleConstants.FontFamily, "monospaced"); bodyStyle.addAttribute(StyleConstants.Bold, true); doc.setLogicalStyle(0, bodyStyle); return codeArea; }
private static void writeWhitespaceNode(DefaultStyledDocument doc, StyleContext styles, Node node, int indent, Collection<IdentifierLocation> idLocations, boolean flagged) throws BadLocationException { if(isWhitespaceNewlineNode(node)) { doc.insertString(doc.getLength(), "\n", styles.getStyle(STYLE_WS)); if(indent > 0) { doc.insertString(doc.getLength(), indent(indent), styles.getStyle(STYLE_WS)); } } else if(isWhitespaceIndentNode(node)) { doc.insertString(doc.getLength(), indent(1), styles.getStyle(STYLE_WS)); NodeList children = node.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { write(doc, styles, children.item(i), indent + 1, idLocations, flagged); } } else { doc.insertString(doc.getLength(), " ", styles.getStyle(STYLE_WS)); } }
public static DefaultStyledDocument makeDocument(CoqDocable term, StyleContext styles, Collection<IdentifierLocation> idLocations, String optionalSuffix) { DefaultStyledDocument document = new DefaultStyledDocument(); try { write(document, styles, term.makeCoqDocTerm(CoqDoc.makeDocument()), 0, idLocations, false); if(optionalSuffix != null) { document.insertString(document.getLength(), " ", styles.getStyle(STYLE_WS)); document.insertString(document.getLength(), optionalSuffix, styles.getStyle(STYLE_TEXT)); } } catch(BadLocationException e) { throw new RuntimeException(e); } return document; }
private static void write(DefaultStyledDocument doc, StyleContext styles, Node node, int indent, Collection<IdentifierLocation> idLocations, boolean flagged) throws BadLocationException { if(isWhitespaceNode(node)) { writeWhitespaceNode(doc, styles, node, indent, idLocations, flagged); } else if(isTextNode(node)) { writeTextNode(doc, styles, node, indent, idLocations, flagged); } else if(isKeywordNode(node)) { writeKeywordNode(doc, styles, node, indent, idLocations, flagged); } else if(isIdentifierNode(node)) { writeIdentifierNode(doc, styles, node, indent, idLocations, flagged); } else if(isTermNode(node)) { writeTermNode(doc, styles, node, indent, idLocations, flagged); } else if(isFlaggedNode(node)) { writeFlaggedNode(doc, styles, node, indent, idLocations, true); } else { throw new IllegalArgumentException("Unknown node type: " + XMLUtils.nodeToString(node)); } }
private Font extractFont(final StyleContext style, final int pos, final Element rootElement, final AttributeSet attributes) { Font font = null; if (attributes.isDefined(StyleConstants.FontSize) || attributes.isDefined(StyleConstants.FontFamily)) { font = style.getFont(attributes); } if (font == null) { if (document instanceof DefaultStyledDocument) { font = extractFontFromDefaultStyledDocument((DefaultStyledDocument) document, style, pos, rootElement); } else { font = style.getFont(rootElement.getAttributes()); } } return font; }
/** * {@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(); } }
/** * Write the styles used. */ protected void writeStyles() throws IOException { if(doc instanceof DefaultStyledDocument) { Enumeration<?> styles = ((DefaultStyledDocument)doc).getStyleNames(); while(styles.hasMoreElements()) writeStyle(doc.getStyle((String)styles.nextElement())); } else { // What else to do here? Style s = doc.getStyle("default"); if(s != null) writeStyle( s ); } }
/** * Instructs the parse buffer to create a block element with the given * attributes. * * @param t the tag that requires opening a new block * @param attr the attribute set for the new block */ protected void blockOpen(HTML.Tag t, MutableAttributeSet attr) { if (inImpliedParagraph()) blockClose(HTML.Tag.IMPLIED); // Push the new tag on top of the stack. parseStack.push(t); DefaultStyledDocument.ElementSpec element; AbstractDocument.AttributeContext ctx = getAttributeContext(); AttributeSet copy = attr.copyAttributes(); copy = ctx.addAttribute(copy, StyleConstants.NameAttribute, t); element = new DefaultStyledDocument.ElementSpec(copy, DefaultStyledDocument.ElementSpec.StartTagType); parseBuffer.addElement(element); }
/** * Adds content that is specified in the attribute set. * * @param t the HTML.Tag * @param a the attribute set specifying the special content */ protected void addSpecialElement(HTML.Tag t, MutableAttributeSet a) { if (t != HTML.Tag.FRAME && ! inParagraph()) { blockOpen(HTML.Tag.IMPLIED, new SimpleAttributeSet()); } a.addAttribute(StyleConstants.NameAttribute, t); // The two spaces are required because some special elements like HR // must be broken. At least two characters are needed to break into the // two parts. DefaultStyledDocument.ElementSpec spec = new DefaultStyledDocument.ElementSpec(a.copyAttributes(), DefaultStyledDocument.ElementSpec.ContentType, new char[] {' '}, 0, 1 ); parseBuffer.add(spec); }
@Test public void testTrim() throws Exception { final StyledDocument doc = new DefaultStyledDocument(); final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 10; i++) { buffer.append("\n"); } doc.insertString(0, buffer.toString(), 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()); }
/** * Write the styles used. */ protected void writeStyles() throws IOException { if(doc instanceof DefaultStyledDocument) { Enumeration styles = ((DefaultStyledDocument)doc).getStyleNames(); while(styles.hasMoreElements()) writeStyle(doc.getStyle((String)styles.nextElement())); } else { // What else to do here? Style s = doc.getStyle("default"); if(s != null) writeStyle( s ); } }
/** * Functie proprie de initializare */ private void initialize() { this.setViewportView(textpane); textpane.setBorder(BorderFactory.createLoweredBevelBorder()); textpane.setBackground(Color.WHITE); StyledDocument styleDocument = new DefaultStyledDocument(); SimpleAttributeSet center = new SimpleAttributeSet(); StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER); styleDocument.setParagraphAttributes(0, styleDocument.getLength(), center, false); textpane.setDocument(styleDocument); //No focus listener because te tab key will erase the values // textarea.addFocusListener(new FocusAdapter() { // @Override // public void focusGained(FocusEvent e) { // textarea.selectAll(); // } // }); //Inregistrez ascultatorii editorChangeListeners = new Vector<IEditorChangeListener>(); textpane.getDocument().addDocumentListener(this); }
/** * Se seteaza valoarea ce se editeaza * @param objectClass * @param renderedObject */ public void setValue(Class objectClass, Object renderedObject) { String auxString; //Setez obiectul in textfield try { if (String.class == objectClass) { auxString = (String) renderedObject; StyledDocument styleDocument = new DefaultStyledDocument(); AttributeSet attributeSet = textpane.getParagraphAttributes(); styleDocument.insertString(0, auxString, null); styleDocument.setParagraphAttributes(0, styleDocument.getLength(), attributeSet, false); textpane.setDocument(styleDocument); } else throw new UnsupportedOperationException(objectClass+" not supported in JTextArea"); } catch (BadLocationException ex) { Logger.getLogger(JTextPanePropertiesEditor.class.getName()).log(Level.WARNING, "bad location", ex); } }
private void showWords() { ACEText<OWLEntity, OWLLogicalAxiom> acetext = ACETextManager.getActiveACEText(); int contentWordCount = acetext.getReferencedEntities().size(); int sentenceCount = acetext.getSentences().size(); String pl1 = ""; String pl2 = ""; if (contentWordCount > 1) { pl1 = "s"; } if (sentenceCount > 1) { pl2 = "s"; } getView().setHeaderText(contentWordCount + " content word" + pl1 + " in " + sentenceCount + " sentence" + pl2); if (contentWordCount > 0) { textpaneWords.setDocument(getContentWordsAsStyledDocument(acetext, owlRendererPreferences.getFont())); } else { textpaneWords.setDocument(new DefaultStyledDocument()); } }
/** * <p>Shows the answer to the given snippet (i.e. a question) in the * given ACE text.</p> * * <p>Every answer is an OWL entity. The entities are grouped into * three groups: individuals, sub classes, super classes. Clicking * on the entity selects the ACE snippet that represents the * full answer, and selects the clicked entity.</p> * * @param acetext ACE text * @param question ACE question */ public void showAnswer(ACEText acetext, ACESnippet question) { setDocument(new DefaultStyledDocument()); doc = new DefaultStyledDocument(); if (question.hasAxioms()) { ACEAnswer answer = acetext.getAnswer(question); if (answer == null) { } else { final OWLDescription dlquery = question.getDLQuery(); if (answer.isSatisfiable()) { showAnswers(dlquery, answer); } else { showNothingSnippet(dlquery); } } } else { addComponent(ComponentFactory.makeItalicLabel("This question could not be mapped to OWL (i.e. DL Query).")); } setDocument(doc); }
/** * Set the content of the syntax highlighter. It is better to set other * settings first and set this the last. * * @param content the content to set */ public void setContent(String content) { String newContent = content == null ? "" : content; DefaultStyledDocument document = (DefaultStyledDocument) getDocument(); try { document.remove(0, document.getLength()); if (theme != null) { document.insertString(0, newContent, theme.getPlain().getAttributeSet()); } else { document.insertString(0, newContent, new SimpleAttributeSet()); } } catch (BadLocationException ex) { LOG.log(Level.SEVERE, null, ex); } //setCaretPosition(0); // clear the style list styleList = null; }
/** * Apply the list of style to the script text pane. See * {@link syntaxhighlighter.parser.Parser#parse(syntaxhighlighter.brush.Brush, boolean, char[], int, int)}. */ protected void applyStyle() { if (theme == null || styleList == null) { return; } DefaultStyledDocument document = (DefaultStyledDocument) getDocument(); // clear all the existing style document.setCharacterAttributes(0, document.getLength(), theme.getPlain().getAttributeSet(), true); // apply style according to the style list for (String key : styleList.keySet()) { List<ParseResult> posList = styleList.get(key); SimpleAttributeSet attributeSet = theme.getStyle(key).getAttributeSet(); for (ParseResult pos : posList) { document.setCharacterAttributes(pos.getOffset(), pos.getLength(), attributeSet, true); } } 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, 18); 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); }
public static StyledDocument createStyleDocument() { StyleContext styleContext= new StyleContext(); Color grey= new Color(0.95f, 0.95f, 0.95f); Color color= UIManager.getColor("EditorPane.background"); if (!color.equals(Color.WHITE)) { grey= new Color(0.25f, 0.25f, 0.25f); } Color orange= new Color(Integer.parseInt("008EFF", 16)); createStyle(styleContext, DEFAULT_STYLE, Color.black, "monospaced", color, 11, null); createStyle(styleContext, CURSOR_STYLE, new Color(0.8f, 0, 0), "monospaced", grey, 11, null); createStyle(styleContext, CURLY_STYLE, Color.BLACK, "monospaced", color, 11, true); createStyle(styleContext, FETCH_STYLE, new Color(0, 0.5f, 0), "monospaced", grey, 11, null); createStyle(styleContext, SPECIAL_STYLE, new Color(0.5f, 0.5f, 0), "monospaced", grey, 11, null); createStyle(styleContext, PRODUCTION_FOUND_STYLE, Color.BLUE, "monospaced", grey, 11, true); createStyle(styleContext, PRODUCTION_BEFORE_REPLACEMENT_STYLE, orange, "monospaced", grey, 11, true); return new DefaultStyledDocument(styleContext); }
protected void writeStyles() throws IOException { if (!(getDocument() instanceof DefaultStyledDocument)) { // XXX: it's not clear what to do in this case throw new UnsupportedOperationException(Messages.getString("swing.9F")); //$NON-NLS-1$ } StyledDocument styledDocument = (StyledDocument)getDocument(); Enumeration styles = ((DefaultStyledDocument)getDocument()).getStyleNames(); while (styles.hasMoreElements()) { String styleName = (String)styles.nextElement(); if (StyleSheet.DEFAULT_STYLE.equals(styleName)) { continue; } indent(); write("p." + styleName + " {"); writeLineSeparator(); incrIndent(); writeAttributes(styledDocument.getStyle(styleName)); decrIndent(); indent(); write("}"); writeLineSeparator(); } }
private void checkSpecType(final String specsDescr, int i, final DefaultStyledDocument.ElementSpec spec) { final char typeChar = specsDescr.charAt(i*2); short specType = 0; if (typeChar == 's') { specType = ElementSpec.StartTagType; } else if (typeChar == 'c') { specType = ElementSpec.ContentType; } else if (typeChar == 'e') { specType = ElementSpec.EndTagType; } final char dirChar = specsDescr.charAt(i*2 + 1); short specDir = 0; if (dirChar == 'n') { specDir = ElementSpec.JoinNextDirection; } else if (dirChar == 'p') { specDir = ElementSpec.JoinPreviousDirection; } else if (dirChar == 'o') { specDir = ElementSpec.OriginateDirection; } assertEquals("spec direction", specDir, spec.getDirection()); assertEquals("spec type", specType, spec.getType()); }
public void testWrite() throws Exception { StringWriter writer = new StringWriter(); final String content = "Hello, World!"; final int start = 1; final int end = 4; DefaultStyledDocument doc = new DefaultStyledDocument(); doc.insertString(0, content, null); editorKit.write(writer, doc, start, end); String output = writer.toString(); assertTrue(output.indexOf("<html>") != -1); if (isHarmony()) { assertFalse(output.indexOf(content) != -1); assertTrue(output.indexOf(content.substring(start, end)) != -1); } writer = new StringWriter(); doc = (HTMLDocument)editorKit.createDefaultDocument(); doc.insertString(0, content, null); editorKit.write(writer, doc, start, end); output = writer.toString(); assertTrue(output.indexOf("<html>") != -1); assertFalse(output.indexOf(content) != -1); assertTrue(output.indexOf(content.substring(start, end)) != -1); }
public void testSetDocument() { StyledDocument doc = new DefaultStyledDocument(); textPane.setDocument(doc); assertSame(doc, textPane.getDocument()); testExceptionalCase(new IllegalArgumentCase() { @Override public void exceptionalAction() throws Exception { textPane.setDocument(new PlainDocument()); } }); testExceptionalCase(new IllegalArgumentCase() { @Override public void exceptionalAction() throws Exception { textPane.setDocument(null); } }); }
private void initStyles() { // cr�ation des styles n�cessaires TEMPLATE = new DefaultStyledDocument(); COMMENT_STYLE = TEMPLATE.addStyle("comment", null); StyleConstants.setItalic(COMMENT_STYLE, true); StyleConstants.setForeground(COMMENT_STYLE , COMMENT_COLOR); DEFAULT_STYLE = TEMPLATE.addStyle("default", null); PARAM_STYLE = TEMPLATE.addStyle("param", null); StyleConstants.setBold(PARAM_STYLE, true); StyleConstants.setForeground(PARAM_STYLE, PARAM_COLOR); KEYWORD_STYLE = TEMPLATE.addStyle("kw", null); StyleConstants.setBold(KEYWORD_STYLE, true); StyleConstants.setForeground(KEYWORD_STYLE, KEYWORD_COLOR); LINK_STYLE = TEMPLATE.addStyle("link", null); StyleConstants.setBold(LINK_STYLE, true); StyleConstants.setForeground(LINK_STYLE, KEYWORD_COLOR); StyleConstants.setUnderline(LINK_STYLE, true); HILIGHT_STYLE = TEMPLATE.addStyle("hl", null); StyleConstants.setBackground(HILIGHT_STYLE, HILIGHT_COLOR); }
/** * Create a new PlexMessageWindow with the given title. * <p> * @param title Title string for the window. */ public PlexMessageWindow(String title) { frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); context = new StyleContext(); document = new DefaultStyledDocument(context); style = context.getStyle(StyleContext.DEFAULT_STYLE); StyleConstants.setAlignment(style, StyleConstants.ALIGN_LEFT); StyleConstants.setFontSize(style, 14); //StyleConstants.setSpaceAbove(style, 1); //StyleConstants.setSpaceBelow(style, 1); textPane = new JTextPane(document); textPane.setEditable(false); scrollPane = new JScrollPane(textPane); frame.add(scrollPane, BorderLayout.CENTER); frame.setSize(300, 150); }