javax.swing.text.Element Java Examples

The following examples show how to use javax.swing.text.Element. 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
Source File: GapBoxView.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Get the offset area in which the views should be rebuilt
 * in reaction to insert update in the underlying document.
 *
 * @param evt document event for the document modification.
 * @return two-item integer array containing starting and ending offset
 *  of the area to be rebuilt or <code>null</code> in case
 *  no views should be rebuilt.
 */
protected int[] getRemoveUpdateRebuildOffsetRange(DocumentEvent evt) {
    DocumentEvent.ElementChange lineChange = evt.getChange(evt.getDocument().getDefaultRootElement());
    if (lineChange == null) {
        return null;
    }

    int startOffset = evt.getOffset();
    int endOffset = startOffset;
    int[] offsetRange = new int[] {startOffset, endOffset};
    Element[] addedLines = lineChange.getChildrenAdded();
    ElementUtilities.updateOffsetRange(addedLines, offsetRange);
    Element[] removedLines = lineChange.getChildrenRemoved();
    ElementUtilities.updateOffsetRange(removedLines, offsetRange);
    return offsetRange;
}
 
Example #2
Source File: InlineReplacedBoxView.java    From SwingBox with GNU Lesser General Public License v3.0 6 votes vote down vote up
public InlineReplacedBoxView(Element elem)
{
    super(elem);

    content = ((InlineReplacedBox) box).getContentObj();
    if (content instanceof ReplacedImage)
    {
        repImage = (ReplacedImage) content;
    }
    else
    {
        repImage = null;
    }

    loadElementAttributes();
}
 
Example #3
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override public View create(Element elem) {
  switch (elem.getName()) {
    // case AbstractDocument.ContentElementName:
    //   return new LabelView(elem);
    case AbstractDocument.ParagraphElementName:
      return new ParagraphWithEndMarkView(elem);
    case AbstractDocument.SectionElementName:
      return new BoxView(elem, View.Y_AXIS);
    case StyleConstants.ComponentElementName:
      return new ComponentView(elem);
    case StyleConstants.IconElementName:
      return new IconView(elem);
    default:
      return new LabelView(elem);
  }
}
 
Example #4
Source File: NumberedViewFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public View create(Element elem) {
    String kind = elem.getName();
    // System.out.println("Kind: " + kind);
    if (kind != null) {
        if (AbstractDocument.ContentElementName.equals(kind)) {
            return new LabelView(elem);
        } else if (AbstractDocument.ParagraphElementName.equals(kind)) {
            return new NumberedParagraphView(elem, highlight);
        } else if (AbstractDocument.SectionElementName.equals(kind)) {
            return new NoWrapBoxView(elem, View.Y_AXIS);
        } else if (StyleConstants.ComponentElementName.equals(kind)) {
            return new ComponentView(elem);
        } else if (StyleConstants.IconElementName.equals(kind)) {
            return new IconView(elem);
        }
    }
    // default to text display
    return new LabelView(elem);
}
 
Example #5
Source File: MITextEditorPane.java    From MeteoInfo with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String getCurrentText() {
    Document doc = this.getDocument();
    int dot = this.getCaretPosition();
    Element root = doc.getDefaultRootElement();
    int index = root.getElementIndex(dot);
    Element elem = root.getElement(index);
    int start = elem.getStartOffset();
    int len = dot - start;
    try {
        doc.getText(start, len, seg);
    } catch (BadLocationException ble) {
        ble.printStackTrace();
        return "";
    }
    return seg.toString();
}
 
Example #6
Source File: HyperlinkSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void mouseClicked(MouseEvent e) {
    try {
        if (SwingUtilities.isLeftMouseButton(e)) {
            JTextPane pane = (JTextPane)e.getSource();
            StyledDocument doc = pane.getStyledDocument();
            Element elem = doc.getCharacterElement(pane.viewToModel(e.getPoint()));
            AttributeSet as = elem.getAttributes();
            Link link = (Link)as.getAttribute(LINK_ATTRIBUTE);
            if (link != null) {
                link.onClick(elem.getDocument().getText(elem.getStartOffset(), elem.getEndOffset() - elem.getStartOffset()));
            }
        }
    } catch(Exception ex) {
        Support.LOG.log(Level.SEVERE, null, ex);
    }
}
 
Example #7
Source File: Test6933784.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void checkImages() throws Exception {
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            HTMLEditorKit c = new HTMLEditorKit();
            HTMLDocument doc = new HTMLDocument();

            try {
                c.read(new StringReader("<HTML><TITLE>Test</TITLE><BODY><IMG id=test></BODY></HTML>"), doc, 0);
            } catch (Exception e) {
                throw new RuntimeException("The test failed", e);
            }

            Element elem = doc.getElement("test");
            ImageView iv = new ImageView(elem);

            if (iv.getLoadingImageIcon() == null) {
                throw new RuntimeException("getLoadingImageIcon returns null");
            }

            if (iv.getNoImageIcon() == null) {
                throw new RuntimeException("getNoImageIcon returns null");
            }
        }
    });
}
 
Example #8
Source File: ElementTreePanel.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Called whenever the value of the selection changes.
 * @param e the event that characterizes the change.
 */
public void valueChanged(TreeSelectionEvent e) {

    if (!updatingSelection && tree.getSelectionCount() == 1) {
        TreePath selPath = tree.getSelectionPath();
        Object lastPathComponent = selPath.getLastPathComponent();

        if (!(lastPathComponent instanceof DefaultMutableTreeNode)) {
            Element selElement = (Element) lastPathComponent;

            updatingSelection = true;
            try {
                getEditor().select(selElement.getStartOffset(),
                        selElement.getEndOffset());
            } finally {
                updatingSelection = false;
            }
        }
    }
}
 
Example #9
Source File: CustomTextPane.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public View create(final Element element) {
  final String kind = element.getName();
  if (kind != null) {
    switch (kind) {
      case AbstractDocument.ContentElementName:
        return new WrapLabelView(element);
      case AbstractDocument.ParagraphElementName:
        return new ParagraphView(element);
      case AbstractDocument.SectionElementName:
        return new BoxView(element, View.Y_AXIS);
      case StyleConstants.ComponentElementName:
        return new ComponentView(element);
      case StyleConstants.IconElementName:
        return new IconView(element);
    }
  }

  // Default to text display.
  return new LabelView(element);
}
 
Example #10
Source File: SmartHomeAction.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
static int getSmartHomeOffset(JTextComponent target, SyntaxDocument sDoc,
        int dot) throws BadLocationException {
    Element el = sDoc.getParagraphElement(dot);
    Segment seg = new Segment();
    sDoc.getText(el.getStartOffset(),
            el.getEndOffset() - el.getStartOffset() - 1, seg);
    int homeOffset = 0;
    int dotLineOffset = dot - el.getStartOffset();
    boolean inText = false;
    // see the location of first non-space offset
    for (int i = 0; i < dotLineOffset; i++) {
        if (!Character.isWhitespace(seg.charAt(i))) {
            inText = true;
            break;
        }
    }
    // if we are at first char in line, or we are past the non space
    // chars in the line, then we move to non-space char
    // otherwise, we move to first char of line
    if (dotLineOffset == 0 || inText) {
        for (char ch = seg.first();
                ch != CharacterIterator.DONE && Character.isWhitespace(ch);
                ch = seg.next()) {
            homeOffset++;
        }
    }
    return el.getStartOffset() + homeOffset;
}
 
Example #11
Source File: BatchDocument.java    From android-classyshark with Apache License 2.0 5 votes vote down vote up
public void appendBatchLineFeed(AttributeSet a) {
    batch.add(new ElementSpec(
            a, ElementSpec.ContentType, EOL_ARRAY, 0, 1));

    Element paragraph = getParagraphElement(0);
    AttributeSet pattern = paragraph.getAttributes();
    batch.add(new ElementSpec(null, ElementSpec.EndTagType));
    batch.add(new ElementSpec(pattern, ElementSpec.StartTagType));
}
 
Example #12
Source File: AnnotationBar.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Pair method to {@link #annotate}. It releases
 * all resources.
 */
private void release() {
    refreshing = false;
    if (refreshAnnotationsTask != null) {
        refreshAnnotationsTask.cancel();
    }
    if (wcInfo != null) {
        wcInfo.removePropertyChangeListener(this);
    }
    editorUI.removePropertyChangeListener(this);
    textComponent.removeComponentListener(this);
    textComponent.removePropertyChangeListener(this);
    doc.removeDocumentListener(this);
    if (caret != null) {
        caret.removeChangeListener(this);
    }
    if (caretTimer != null) {
        caretTimer.removeActionListener(this);
    }
    elementAnnotations = Collections.<Element, AnnotateLine>emptyMap();
    previousRevisions = null;
    originalFiles = null;
    // cancel running annotation task if active
    if(latestAnnotationTask != null) {
        latestAnnotationTask.cancel();
    }
    AnnotationMarkProvider amp = AnnotationMarkInstaller.getMarkProvider(textComponent);
    if (amp != null) {
        amp.setMarks(Collections.<AnnotationMark>emptyList());
    }

    clearRecentFeedback();
}
 
Example #13
Source File: bug8048110.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static Element findFirstElement(Element e, String name) {
    String elementName = e.getName();
    if (elementName != null && elementName.equalsIgnoreCase(name)) {
        return e;
    }
    for (int i = 0; i < e.getElementCount(); i++) {
        Element result = findFirstElement(e.getElement(i), name);
        if (result != null) {
            return result;
        }
    }
    return null;
}
 
Example #14
Source File: ElementTreePanel.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a TreePath to the element at <code>position</code>.
 */
protected TreePath getPathForIndex(int position, Object root,
        Element rootElement) {
    TreePath path = new TreePath(root);
    Element child = rootElement.getElement(rootElement.getElementIndex(
            position));

    path = path.pathByAddingChild(rootElement);
    path = path.pathByAddingChild(child);
    while (!child.isLeaf()) {
        child = child.getElement(child.getElementIndex(position));
        path = path.pathByAddingChild(child);
    }
    return path;
}
 
Example #15
Source File: bug8058120.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            createAndShowGUI();
        }
    });

    toolkit.realSync();

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                document.insertAfterEnd(document.getElement("ab"), textToInsert);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    });

    toolkit.realSync();

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Element parent = document.getElement("ab").getParentElement();
            int count = parent.getElementCount();
            if (count != 2) {
                throw new RuntimeException("Test Failed! Unexpected Element count = "+count);
            }
            Element insertedElement = parent.getElement(count - 1);
            if (!HTML.Tag.IMPLIED.toString().equals(insertedElement.getName())) {
                throw new RuntimeException("Test Failed! Inserted text is not wrapped by " + HTML.Tag.IMPLIED + " tag");
            }
        }
    });
}
 
Example #16
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private Optional<String> getSpanTitleAttribute(HTMLDocument doc, int pos) {
  // HTMLDocument doc = (HTMLDocument) editor.getDocument();
  Element elem = doc.getCharacterElement(pos);
  // if (!doesElementContainLocation(editor, elem, pos, e.getX(), e.getY())) {
  //   elem = null;
  // }
  // if (elem != null) {
  AttributeSet a = elem.getAttributes();
  AttributeSet span = (AttributeSet) a.getAttribute(HTML.Tag.SPAN);
  return Optional.ofNullable(span).map(s -> Objects.toString(s.getAttribute(HTML.Attribute.TITLE)));
}
 
Example #17
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
public static int getWordStart(JTextComponent c, int offs) throws BadLocationException {
  Element line = Optional.ofNullable(Utilities.getParagraphElement(c, offs))
      .orElseThrow(() -> new BadLocationException("No word at " + offs, offs));
  Document doc = c.getDocument();
  int lineStart = line.getStartOffset();
  int lineEnd = Math.min(line.getEndOffset(), doc.getLength());
  int offs2 = offs;
  Segment seg = SegmentCache.getSharedSegment();
  doc.getText(lineStart, lineEnd - lineStart, seg);
  if (seg.count > 0) {
    BreakIterator words = BreakIterator.getWordInstance(c.getLocale());
    words.setText(seg);
    int wordPosition = seg.offset + offs - lineStart;
    if (wordPosition >= words.last()) {
      wordPosition = words.last() - 1;
      words.following(wordPosition);
      offs2 = lineStart + words.previous() - seg.offset;
    } else {
      words.following(wordPosition);
      offs2 = lineStart + words.previous() - seg.offset;
      for (int i = offs; i > offs2; i--) {
        char ch = seg.charAt(i - seg.offset);
        if (ch == '_' || ch == '-') {
          offs2 = i + 1;
          break;
        }
      }
    }
  }
  SegmentCache.releaseSharedSegment(seg);
  return offs2;
}
 
Example #18
Source File: Test6968363.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Element[] getRootElements() {
    Element[] elements = this.document.getRootElements();
    Element[] wrappers = new Element[elements.length];
    for (int i = 0; i < elements.length; i++) {
        wrappers[i] = new MyElement(elements[i]);
    }
    return wrappers;
}
 
Example #19
Source File: bug8058120.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            createAndShowGUI();
        }
    });

    toolkit.realSync();

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                document.insertAfterEnd(document.getElement("ab"), textToInsert);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    });

    toolkit.realSync();

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Element parent = document.getElement("ab").getParentElement();
            int count = parent.getElementCount();
            if (count != 2) {
                throw new RuntimeException("Test Failed! Unexpected Element count = "+count);
            }
            Element insertedElement = parent.getElement(count - 1);
            if (!HTML.Tag.IMPLIED.toString().equals(insertedElement.getName())) {
                throw new RuntimeException("Test Failed! Inserted text is not wrapped by " + HTML.Tag.IMPLIED + " tag");
            }
        }
    });
}
 
Example #20
Source File: CommentsPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void setVisible(boolean b) {
    if (b) {
        JTextPane pane = (JTextPane) getInvoker();
        StyledDocument doc = pane.getStyledDocument();
        Element elem = doc.getCharacterElement(pane.viewToModel(clickPoint));
        Object l = elem.getAttributes().getAttribute(HyperlinkSupport.LINK_ATTRIBUTE);
        if (l != null && l instanceof AttachmentLink) {
            BugzillaIssue.Attachment attachment = ((AttachmentLink) l).attachment;
            if (attachment != null) {
                add(new JMenuItem(attachment.getOpenAction()));
                add(new JMenuItem(attachment.getSaveAction()));
                Action openInStackAnalyzerAction = attachment.getOpenInStackAnalyzerAction();
                if(openInStackAnalyzerAction != null) {
                    add(new JMenuItem(openInStackAnalyzerAction));
                }
                if (attachment.isPatch()) { 
                    Action a = attachment.getApplyPatchAction();
                    if(a != null) {
                        add(attachment.getApplyPatchAction());
                    }
                }
                super.setVisible(true);
            }
        }
    } else {
        super.setVisible(false);
        removeAll();
    }
}
 
Example #21
Source File: bug8058120.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            createAndShowGUI();
        }
    });

    toolkit.realSync();

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                document.insertAfterEnd(document.getElement("ab"), textToInsert);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    });

    toolkit.realSync();

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Element parent = document.getElement("ab").getParentElement();
            int count = parent.getElementCount();
            if (count != 2) {
                throw new RuntimeException("Test Failed! Unexpected Element count = "+count);
            }
            Element insertedElement = parent.getElement(count - 1);
            if (!HTML.Tag.IMPLIED.toString().equals(insertedElement.getName())) {
                throw new RuntimeException("Test Failed! Inserted text is not wrapped by " + HTML.Tag.IMPLIED + " tag");
            }
        }
    });
}
 
Example #22
Source File: NavigableTextPane.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private int lineToOffset(int line) throws BadLocationException {
    Document d = getDocument();
    try {
        Element element = d.getDefaultRootElement().getElement(line - 1);
        if (element == null) {
            throw new BadLocationException("line " + line + " does not exist", -line);
        }
        return element.getStartOffset();
    } catch (ArrayIndexOutOfBoundsException aioobe) {
        BadLocationException ble = new BadLocationException("line " + line + " does not exist", -line);
        ble.initCause(aioobe);
        throw ble;
    }
}
 
Example #23
Source File: SyntaxDocument.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the line at given position. The line returned will NOT include the
 * line terminator '\n'
 *
 * @param pos Position (usually from text.getCaretPosition()
 * @return the STring of text at given position
 * @throws BadLocationException
 */
public String getLineAt(int pos) throws BadLocationException {
    Element e = getParagraphElement(pos);
    Segment seg = new Segment();
    getText(e.getStartOffset(), e.getEndOffset() - e.getStartOffset(), seg);
    char last = seg.last();
    if (last == '\n' || last == '\r') {
        seg.count--;
    }
    return seg.toString();
}
 
Example #24
Source File: CAccessibleText.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
    Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return null;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();
    final Element line = root.getElement(lineIndex);
    if (line == null) return null;

    return new int[] { line.getStartOffset(), line.getEndOffset() };
}
 
Example #25
Source File: LineRootElement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Element getElement(int index) {
    if (index < 0) {
        throw new IndexOutOfBoundsException("Invalid line index=" + index + " < 0"); // NOI18N
    }
    int elementCount = getElementCount();
    if (index >= elementCount) {
        throw new IndexOutOfBoundsException("Invalid line index=" + index // NOI18N
            + " >= lineCount=" + elementCount); // NOI18N
    }
    
    return super.getElement(index);
}
 
Example #26
Source File: ElementTreePanel.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Updates the tree based on the event type. This will invoke either
 * updateTree with the root element, or handleChange.
 */
protected void updateTree(DocumentEvent event) {
    updatingSelection = true;
    try {
        TreeModel model = getTreeModel();
        Object root = model.getRoot();

        for (int counter = model.getChildCount(root) - 1; counter >= 0;
                counter--) {
            updateTree(event, (Element) model.getChild(root, counter));
        }
    } finally {
        updatingSelection = false;
    }
}
 
Example #27
Source File: CAccessibleText.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static int getLineNumberForIndex(final Accessible a, int index) {
    final Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return -1;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();

    // treat -1 special, returns the current caret position
    if (index == -1) index = jc.getCaretPosition();

    // Determine line number (can be -1)
    return root.getElementIndex(index);
}
 
Example #28
Source File: CAccessibleText.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
    Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return null;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();
    final Element line = root.getElement(lineIndex);
    if (line == null) return null;

    return new int[] { line.getStartOffset(), line.getEndOffset() };
}
 
Example #29
Source File: bug6857057.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
bug6857057() {
    Element elem = new StubBranchElement(" G L Y P H V");
    GlyphView view = new GlyphView(elem);
    float pos = elem.getStartOffset();
    float len = elem.getEndOffset() - pos;
    int res = view.getBreakWeight(View.X_AXIS, pos, len);
    if (res != View.ExcellentBreakWeight) {
        throw new RuntimeException("breakWeight != ExcellentBreakWeight");
    }
}
 
Example #30
Source File: bug8048110.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static Element findFirstElement(Element e, String name) {
    String elementName = e.getName();
    if (elementName != null && elementName.equalsIgnoreCase(name)) {
        return e;
    }
    for (int i = 0; i < e.getElementCount(); i++) {
        Element result = findFirstElement(e.getElement(i), name);
        if (result != null) {
            return result;
        }
    }
    return null;
}