List of usage examples for javax.swing.text Document getDefaultRootElement
public Element getDefaultRootElement();
From source file:Main.java
public static void main(String[] argv) throws Exception { JTextArea textArea = new JTextArea("word1 word2\nword3\nword4"); Document doc = textArea.getDocument(); ElementIterator it = new ElementIterator(doc.getDefaultRootElement()); Element e;/* www . j a v a2s .c o m*/ while ((e = it.next()) != null) { if (e.isLeaf()) { int rangeStart = e.getStartOffset(); int rangeEnd = e.getEndOffset(); String line = textArea.getText(rangeStart, rangeEnd - rangeStart); System.out.println(line); } } }
From source file:Main.java
private static final Element getLineElem(Document d, int offs) { Element map = d.getDefaultRootElement(); int index = map.getElementIndex(offs); Element elem = map.getElement(index); if ((offs >= elem.getStartOffset()) && (offs < elem.getEndOffset())) { return elem; }//from w w w . j a v a 2 s . co m return null; }
From source file:ShowHTMLViews.java
public static void displayModel(JTextComponent comp, PrintStream out) { Document doc = comp.getDocument(); Element e = doc.getDefaultRootElement(); displayElement(doc, e, 0, out);//w w w . j a v a 2s. c o m }
From source file:Main.java
protected static int getLineOfOffset(int offset, Document doc) throws BadLocationException { if (offset < 0 || doc == null) { throw new BadLocationException("", -1); } else if (offset > doc.getLength()) { throw new BadLocationException("", doc.getLength() + 1); } else {/*from ww w. j a v a 2s . com*/ Element map = doc.getDefaultRootElement(); return map.getElementIndex(offset); } }
From source file:Main.java
private String addWhiteSpace(FilterBypass fb, int offset, String text) throws BadLocationException { Document doc = fb.getDocument(); Element root = doc.getDefaultRootElement(); int line = root.getElementIndex(offset); int i = root.getElement(line).getStartOffset(); StringBuilder whiteSpace = new StringBuilder(text); while (true) { String temp = doc.getText(i, 1); if (temp.equals(" ") || temp.equals("\t")) { System.out.println("added"); whiteSpace.append(temp);//from w w w. ja va 2 s. c om i++; } else { break; } } return whiteSpace.toString(); }
From source file:ListenerSample.java
public void printInfo(DocumentEvent documentEvent) { System.out.println("Offset: " + documentEvent.getOffset()); System.out.println("Length: " + documentEvent.getLength()); DocumentEvent.EventType type = documentEvent.getType(); String typeString = null;/* w w w. j a v a2s.co m*/ if (type.equals(DocumentEvent.EventType.CHANGE)) { typeString = "Change"; } else if (type.equals(DocumentEvent.EventType.INSERT)) { typeString = "Insert"; } else if (type.equals(DocumentEvent.EventType.REMOVE)) { typeString = "Remove"; } System.out.println("Type : " + typeString); Document documentSource = documentEvent.getDocument(); Element rootElement = documentSource.getDefaultRootElement(); DocumentEvent.ElementChange change = documentEvent.getChange(rootElement); System.out.println("Change: " + change); }
From source file:net.sf.jasperreports.engine.util.JEditorPaneRtfMarkupProcessor.java
@Override public String convert(String srcText) { JEditorPane editorPane = new JEditorPane("text/rtf", srcText); editorPane.setEditable(false);/*from ww w. j a v a2 s . com*/ List<Element> elements = new ArrayList<Element>(); Document document = editorPane.getDocument(); Element root = document.getDefaultRootElement(); if (root != null) { addElements(elements, root); } String chunk = null; Element element = null; int startOffset = 0; int endOffset = 0; JRStyledText styledText = new JRStyledText(); styledText.setGlobalAttributes(new HashMap<Attribute, Object>()); for (int i = 0; i < elements.size(); i++) { if (chunk != null) { styledText.append(chunk); styledText.addRun( new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset)); } chunk = null; element = elements.get(i); startOffset = element.getStartOffset(); endOffset = element.getEndOffset(); try { chunk = document.getText(startOffset, endOffset - startOffset); } catch (BadLocationException e) { if (log.isDebugEnabled()) { log.debug("Error converting markup.", e); } } } if (chunk != null && !"\n".equals(chunk)) { styledText.append(chunk); styledText.addRun(new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset)); } return JRStyledTextParser.getInstance().write(styledText); }
From source file:com.mirth.connect.client.ui.components.rsta.ac.js.MirthSourceCompletionProvider.java
@Override public List<Completion> getCompletionsAt(JTextComponent tc, Point p) { Set<Completion> completions = new HashSet<Completion>(); List<Completion> parentCompletions = super.getCompletionsAt(tc, p); if (CollectionUtils.isNotEmpty(parentCompletions)) { completions.addAll(parentCompletions); }// w w w . j a v a 2s.c o m int offset = tc.viewToModel(p); if (offset < 0 || offset >= tc.getDocument().getLength()) { lastCompletionsAtText = null; lastParameterizedCompletionsAt = null; return new ArrayList<Completion>(completions); } Segment s = new Segment(); Document doc = tc.getDocument(); Element root = doc.getDefaultRootElement(); int line = root.getElementIndex(offset); Element elem = root.getElement(line); int start = elem.getStartOffset(); int end = elem.getEndOffset() - 1; try { doc.getText(start, end - start, s); // Get the valid chars before the specified offset. int startOffs = s.offset + (offset - start) - 1; while (startOffs >= s.offset && Character.isLetterOrDigit(s.array[startOffs])) { startOffs--; } // Get the valid chars at and after the specified offset. int endOffs = s.offset + (offset - start); while (endOffs < s.offset + s.count && Character.isLetterOrDigit(s.array[endOffs])) { endOffs++; } int len = endOffs - startOffs - 1; if (len <= 0) { lastParameterizedCompletionsAt = null; return new ArrayList<Completion>(completions); } String text = new String(s.array, startOffs + 1, len); if (text.equals(lastCompletionsAtText)) { if (CollectionUtils.isNotEmpty(lastParameterizedCompletionsAt)) { completions.addAll(lastParameterizedCompletionsAt); } return new ArrayList<Completion>(completions); } lastCompletionsAtText = text; lastParameterizedCompletionsAt = completionCache.getClassCompletions(tc, text); if (CollectionUtils.isNotEmpty(lastParameterizedCompletionsAt)) { completions.addAll(lastParameterizedCompletionsAt); } return new ArrayList<Completion>(completions); } catch (BadLocationException ble) { ble.printStackTrace(); // Never happens } lastCompletionsAtText = null; lastParameterizedCompletionsAt = null; return new ArrayList<Completion>(completions); }
From source file:net.sf.jasperreports.engine.util.JEditorPaneHtmlMarkupProcessor.java
@Override public String convert(String srcText) { JEditorPane editorPane = new JEditorPane("text/html", srcText); editorPane.setEditable(false);//from www.j a v a2 s. c o m List<Element> elements = new ArrayList<Element>(); Document document = editorPane.getDocument(); Element root = document.getDefaultRootElement(); if (root != null) { addElements(elements, root); } int startOffset = 0; int endOffset = 0; int crtOffset = 0; String chunk = null; JRPrintHyperlink hyperlink = null; Element element = null; Element parent = null; boolean bodyOccurred = false; int[] orderedListIndex = new int[elements.size()]; String whitespace = " "; String[] whitespaces = new String[elements.size()]; for (int i = 0; i < elements.size(); i++) { whitespaces[i] = ""; } StringBuilder text = new StringBuilder(); List<JRStyledText.Run> styleRuns = new ArrayList<>(); for (int i = 0; i < elements.size(); i++) { if (bodyOccurred && chunk != null) { text.append(chunk); Map<Attribute, Object> styleAttributes = getAttributes(element.getAttributes()); if (hyperlink != null) { styleAttributes.put(JRTextAttribute.HYPERLINK, hyperlink); hyperlink = null; } if (!styleAttributes.isEmpty()) { styleRuns.add( new JRStyledText.Run(styleAttributes, startOffset + crtOffset, endOffset + crtOffset)); } } chunk = null; element = elements.get(i); parent = element.getParentElement(); startOffset = element.getStartOffset(); endOffset = element.getEndOffset(); AttributeSet attrs = element.getAttributes(); Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute); Object object = (elementName != null) ? null : attrs.getAttribute(StyleConstants.NameAttribute); if (object instanceof HTML.Tag) { HTML.Tag htmlTag = (HTML.Tag) object; if (htmlTag == Tag.BODY) { bodyOccurred = true; crtOffset = -startOffset; } else if (htmlTag == Tag.BR) { chunk = "\n"; } else if (htmlTag == Tag.OL) { orderedListIndex[i] = 0; String parentName = parent.getName().toLowerCase(); whitespaces[i] = whitespaces[elements.indexOf(parent)] + whitespace; if (parentName.equals("li")) { chunk = ""; } else { chunk = "\n"; ++crtOffset; } } else if (htmlTag == Tag.UL) { whitespaces[i] = whitespaces[elements.indexOf(parent)] + whitespace; String parentName = parent.getName().toLowerCase(); if (parentName.equals("li")) { chunk = ""; } else { chunk = "\n"; ++crtOffset; } } else if (htmlTag == Tag.LI) { whitespaces[i] = whitespaces[elements.indexOf(parent)]; if (element.getElement(0) != null && (element.getElement(0).getName().toLowerCase().equals("ol") || element.getElement(0).getName().toLowerCase().equals("ul"))) { chunk = ""; } else if (parent.getName().equals("ol")) { int index = elements.indexOf(parent); Object type = parent.getAttributes().getAttribute(HTML.Attribute.TYPE); Object startObject = parent.getAttributes().getAttribute(HTML.Attribute.START); int start = startObject == null ? 0 : Math.max(0, Integer.valueOf(startObject.toString()) - 1); String suffix = ""; ++orderedListIndex[index]; if (type != null) { switch (((String) type).charAt(0)) { case 'A': suffix = getOLBulletChars(orderedListIndex[index] + start, true); break; case 'a': suffix = getOLBulletChars(orderedListIndex[index] + start, false); break; case 'I': suffix = JRStringUtil.getRomanNumeral(orderedListIndex[index] + start, true); break; case 'i': suffix = JRStringUtil.getRomanNumeral(orderedListIndex[index] + start, false); break; case '1': default: suffix = String.valueOf(orderedListIndex[index] + start); break; } } else { suffix += orderedListIndex[index] + start; } chunk = whitespaces[index] + suffix + DEFAULT_BULLET_SEPARATOR + " "; } else { chunk = whitespaces[elements.indexOf(parent)] + DEFAULT_BULLET_CHARACTER + " "; } crtOffset += chunk.length(); } else if (element instanceof LeafElement) { if (element instanceof RunElement) { RunElement runElement = (RunElement) element; AttributeSet attrSet = (AttributeSet) runElement.getAttribute(Tag.A); if (attrSet != null) { hyperlink = new JRBasePrintHyperlink(); hyperlink.setHyperlinkType(HyperlinkTypeEnum.REFERENCE); hyperlink.setHyperlinkReference((String) attrSet.getAttribute(HTML.Attribute.HREF)); hyperlink.setLinkTarget((String) attrSet.getAttribute(HTML.Attribute.TARGET)); } } try { chunk = document.getText(startOffset, endOffset - startOffset); } catch (BadLocationException e) { if (log.isDebugEnabled()) { log.debug("Error converting markup.", e); } } } } } if (chunk != null) { if (!"\n".equals(chunk)) { text.append(chunk); Map<Attribute, Object> styleAttributes = getAttributes(element.getAttributes()); if (hyperlink != null) { styleAttributes.put(JRTextAttribute.HYPERLINK, hyperlink); hyperlink = null; } if (!styleAttributes.isEmpty()) { styleRuns.add( new JRStyledText.Run(styleAttributes, startOffset + crtOffset, endOffset + crtOffset)); } } else { //final newline, not appending //check if there's any style run that would have covered it, that can happen if there's a <li> tag with style int length = text.length(); for (ListIterator<JRStyledText.Run> it = styleRuns.listIterator(); it.hasNext();) { JRStyledText.Run run = it.next(); //only looking at runs that end at the position where the newline should have been //we don't want to hide bugs in which runs that span after the text length are created if (run.endIndex == length + 1) { if (run.startIndex < run.endIndex - 1) { it.set(new JRStyledText.Run(run.attributes, run.startIndex, run.endIndex - 1)); } else { it.remove(); } } } } } JRStyledText styledText = new JRStyledText(null, text.toString()); for (JRStyledText.Run run : styleRuns) { styledText.addRun(run); } styledText.setGlobalAttributes(new HashMap<Attribute, Object>()); return JRStyledTextParser.getInstance().write(styledText); }
From source file:Main.java
/** * Prints a <code>Document</code> using a monospaced font, word wrapping on * the characters ' ', '\t', '\n', ',', '.', and ';'. This method is * expected to be called from Printable 'print(Graphics g)' functions. * * @param g The graphics context to write to. * @param doc The <code>javax.swing.text.Document</code> to print. * @param fontSize the point size to use for the monospaced font. * @param pageIndex The page number to print. * @param pageFormat The format to print the page with. * @param tabSize The number of spaces to expand tabs to. * * @see #printDocumentMonospaced/* ww w . j a v a 2 s. co m*/ */ public static int printDocumentMonospacedWordWrap(Graphics g, Document doc, int fontSize, int pageIndex, PageFormat pageFormat, int tabSize) { g.setColor(Color.BLACK); g.setFont(new Font("Monospaced", Font.PLAIN, fontSize)); // Initialize our static variables (these are used by our tab expander below). tabSizeInSpaces = tabSize; fm = g.getFontMetrics(); // Create our tab expander. //RPrintTabExpander tabExpander = new RPrintTabExpander(); // Get width and height of characters in this monospaced font. int fontWidth = fm.charWidth('w'); // Any character will do here, since font is monospaced. int fontHeight = fm.getHeight(); int MAX_CHARS_PER_LINE = (int) pageFormat.getImageableWidth() / fontWidth; int MAX_LINES_PER_PAGE = (int) pageFormat.getImageableHeight() / fontHeight; final int STARTING_LINE_NUMBER = MAX_LINES_PER_PAGE * pageIndex; // The (x,y) coordinate to print at (in pixels, not characters). // Since y is the baseline of where we'll start printing (not the top-left // corner), we offset it by the font's ascent ( + 1 just for good measure). xOffset = (int) pageFormat.getImageableX(); int y = (int) pageFormat.getImageableY() + fm.getAscent() + 1; // A counter to keep track of the number of lines that WOULD HAVE been // printed if we were printing all lines. int numPrintedLines = 0; // Keep going while there are more lines in the document. currentDocLineNumber = 0; // The line number of the document we're currently on. rootElement = doc.getDefaultRootElement(); // To shorten accesses in our loop. numDocLines = rootElement.getElementCount(); // The number of lines in our document. while (currentDocLineNumber < numDocLines) { // Get the line we are going to print. String curLineString; Element currentLine = rootElement.getElement(currentDocLineNumber); int startOffs = currentLine.getStartOffset(); try { curLineString = doc.getText(startOffs, currentLine.getEndOffset() - startOffs); } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); return Printable.NO_SUCH_PAGE; } // Remove newlines, because they end up as boxes if you don't; this is a monospaced font. curLineString = curLineString.replaceAll("\n", ""); // Replace tabs with how many spaces they should be. if (tabSizeInSpaces == 0) { curLineString = curLineString.replaceAll("\t", ""); } else { int tabIndex = curLineString.indexOf('\t'); while (tabIndex > -1) { int spacesNeeded = tabSizeInSpaces - (tabIndex % tabSizeInSpaces); String replacementString = ""; for (int i = 0; i < spacesNeeded; i++) replacementString += ' '; // Note that "\t" is actually a regex for this method. curLineString = curLineString.replaceFirst("\t", replacementString); tabIndex = curLineString.indexOf('\t'); } } // If this document line is too long to fit on one printed line on the page, // break it up into multpile lines. while (curLineString.length() > MAX_CHARS_PER_LINE) { int breakPoint = getLineBreakPoint(curLineString, MAX_CHARS_PER_LINE) + 1; numPrintedLines++; if (numPrintedLines > STARTING_LINE_NUMBER) { g.drawString(curLineString.substring(0, breakPoint), xOffset, y); y += fontHeight; if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE) return Printable.PAGE_EXISTS; } curLineString = curLineString.substring(breakPoint, curLineString.length()); } currentDocLineNumber += 1; // We have printed one more line from the document. numPrintedLines++; if (numPrintedLines > STARTING_LINE_NUMBER) { g.drawString(curLineString, xOffset, y); y += fontHeight; if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE) return Printable.PAGE_EXISTS; } } // Now, the whole document has been "printed." Decide if this page had any text on it or not. if (numPrintedLines > STARTING_LINE_NUMBER) return Printable.PAGE_EXISTS; return Printable.NO_SUCH_PAGE; }