Java Code Examples for javax.swing.text.Element

The following examples show how to use javax.swing.text.Element. 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
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 2
Source Project: netbeans   Source File: GapBoxView.java    License: 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 3
Source Project: java-swing-tips   Source File: MainPanel.java    License: 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
public InlineReplacedBoxView(Element elem)
{
    super(elem);

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

    loadElementAttributes();
}
 
Example 5
Source Project: TencentKona-8   Source File: Test6933784.java    License: 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 6
Source Project: jdk8u60   Source File: ElementTreePanel.java    License: 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 7
Source Project: netbeans   Source File: HyperlinkSupport.java    License: 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 8
Source Project: mzmine2   Source File: CustomTextPane.java    License: 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 9
@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 10
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 11
Source Project: jdk8u_jdk   Source File: ElementTreePanel.java    License: 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 12
Source Project: hottub   Source File: Test6968363.java    License: 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 13
Source Project: java-swing-tips   Source File: MainPanel.java    License: 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 14
Source Project: java-swing-tips   Source File: MainPanel.java    License: 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 15
Source Project: openjdk-jdk9   Source File: Test6968363.java    License: 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 16
Source Project: netbeans   Source File: LockView.java    License: Apache License 2.0 5 votes vote down vote up
public Element getElement() {
    if (view != null) {
        return view.getElement();
    }
    Document doc = getDocument();
    return (doc != null) ? doc.getDefaultRootElement() : null;
}
 
Example 17
Source Project: netbeans   Source File: GapBoxView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Construct a composite box view over the given element.
 *
 * @param elem the element of the model to represent.
 * @param majorAxis the axis to tile along.  This can be
 *  either X_AXIS or Y_AXIS.
 */
public GapBoxView(Element elem, int majorAxis) {
    super(elem);

    if (majorAxis == View.X_AXIS) {
        setStatusBits(X_MAJOR_AXIS_BIT);
    } // by default there should be no bits set
}
 
Example 18
Source Project: jdk8u_jdk   Source File: FPMethodCalledTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void createAndShowGUI(Test test) {

        try {
            UIManager.setLookAndFeel(new MetalLookAndFeel());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        frame = new JFrame();
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(new FlowLayout());

        String text = "AAAAAAA";
        textField = test.isPasswordField()
                ? new JPasswordField(text)
                : new JTextField(text);

        textField.setUI(new MetalTextFieldUI() {

            @Override
            public View create(Element elem) {
                return test.createView(elem);
            }
        });

        panel.add(textField);
        frame.getContentPane().add(panel);
        frame.setVisible(true);
    }
 
Example 19
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 20
Source Project: android-classyshark   Source File: BatchDocument.java    License: 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 21
Source Project: dragonwell8_jdk   Source File: bug8058120.java    License: 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 Project: hottub   Source File: bug8058120.java    License: 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 23
/**
 * 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 24
/**
 * 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 25
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 26
Source Project: jdk8u-jdk   Source File: ElementTreePanel.java    License: 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 Project: TencentKona-8   Source File: bug6857057.java    License: 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 28
Source Project: TencentKona-8   Source File: bug8048110.java    License: 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 29
Source Project: jdk8u-jdk   Source File: CAccessibleText.java    License: 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 30
Source Project: hottub   Source File: CAccessibleText.java    License: 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);
}