javax.swing.text.Element#getAttributes ( )源码实例Demo

下面列出了javax.swing.text.Element#getAttributes ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: wpcleaner   文件: MWPaneSelectionManager.java
/**
 * Select next occurrence of text. 
 */
public void selectNextOccurrence() {
  StyledDocument doc = textPane.getStyledDocument();
  int length = doc.getLength();
  int lastEnd = Integer.MAX_VALUE;
  for (int pos = textPane.getSelectionEnd() + 1; pos < length; pos = lastEnd) {
    Element run = doc.getCharacterElement(pos);
    lastEnd = run.getEndOffset();
    if (pos == lastEnd) {
      // offset + length beyond length of document, bail.
      break;
    }
    MutableAttributeSet attr = (MutableAttributeSet) run.getAttributes();
    if ((attr != null) &&
        (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_TYPE) != null) &&
        (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_OCCURRENCE) != Boolean.FALSE)) {
      select(run);
      return;
    }
  }
  selectFirstOccurrence();
}
 
源代码2 项目: pra   文件: FSwingHtml.java
public static VectorX<Element> matchChild(Element e
			, Attribute ab, String regex){
    VectorX<Element> vE= new VectorX<Element>(Element.class);
    
    int count = e.getElementCount();
    for (int i = 0; i < count; i++) {
      Element c = e.getElement(i);
      AttributeSet mAb = c.getAttributes();
      String s = (String) mAb.getAttribute(ab);	      
      if (s==null)continue;
//    System.out.println(name+" "+ab+"="+s);
      if (s.matches(regex))
        	vE.add(c);

    }
		return vE;
	}
 
源代码3 项目: netbeans   文件: HyperlinkSupport.java
@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);
    }
}
 
源代码4 项目: wpcleaner   文件: MWPaneFormatter.java
/**
 * @param pane Text pane.
 * @param element Element.
 * @return Start of the first element having the same UUID as element.
 */
public static int getUUIDStartOffset(JTextPane pane, Element element) {
  if (element == null) {
    return Integer.MIN_VALUE;
  }
  if (pane == null) {
    return element.getStartOffset();
  }
  Object uuid = element.getAttributes().getAttribute(ATTRIBUTE_UUID);
  if (uuid == null) {
    return element.getStartOffset();
  }
  int startOffset = element.getStartOffset();
  while (startOffset > 0) {
    Element tmpElement = pane.getStyledDocument().getCharacterElement(startOffset - 1);
    if ((tmpElement == null) || (tmpElement.getAttributes() == null)) {
      return startOffset;
    }
    if (!uuid.equals(tmpElement.getAttributes().getAttribute(ATTRIBUTE_UUID))) {
      return startOffset;
    }
    startOffset = tmpElement.getStartOffset();
  }
  return 0;
}
 
源代码5 项目: wpcleaner   文件: MWPaneFormatter.java
/**
 * @param pane Text pane.
 * @param element Element.
 * @return End of the last element having the same UUID as element.
 */
public static int getUUIDEndOffet(JTextPane pane, Element element) {
  if (element == null) {
    return Integer.MAX_VALUE;
  }
  if (pane == null) {
    return element.getEndOffset();
  }
  Object uuid = element.getAttributes().getAttribute(ATTRIBUTE_UUID);
  if (uuid == null) {
    return element.getEndOffset();
  }
  int endOffset = element.getEndOffset();
  int length = pane.getText().length();
  while (endOffset < length) {
    Element tmpElement = pane.getStyledDocument().getCharacterElement(endOffset);
    if ((tmpElement == null) || (tmpElement.getAttributes() == null)) {
      return endOffset;
    }
    if (!uuid.equals(tmpElement.getAttributes().getAttribute(ATTRIBUTE_UUID))) {
      return endOffset;
    }
    endOffset = tmpElement.getEndOffset();
  }
  return length;
}
 
源代码6 项目: birt   文件: RTFParser.java
private static void parseElement( DefaultStyledDocument document,
		Element parent, RTFDocumentHandler handler, boolean lostLast )
{
	for ( int i = 0; i < parent.getElementCount( ); i++ )
	{
		if (lostLast && i==parent.getElementCount( )-1 && parent.getElementCount( ) != 1)
		{
			break;
		}
		Element element = parent.getElement( i );
		AttributeSet attributeset = element.getAttributes( );
		handler.startElement( element.getName( ), attributeset );
		if ( element.getName( ).equalsIgnoreCase( "content" ) )
		{
			try
			{
				int start = element.getStartOffset( );
				int end = element.getEndOffset( );
				String s = document.getText( start, end - start );
				handler.content( s );
			}
			catch ( BadLocationException e )
			{
			}
		}
		parseElement( document, element, handler, false );
		handler.endElement( element.getName( ) );
	}
}
 
源代码7 项目: pra   文件: FSwingHtml.java
public static boolean hasAttribute(Element e, Attribute ab){
	AttributeSet mAb=e.getAttributes();
   for (Enumeration it = mAb.getAttributeNames() ; it.hasMoreElements() ;) {
   	Object s= it.nextElement();
     if (s.equals(ab))
     	return true;
   }
	return false;		
}
 
源代码8 项目: java-swing-tips   文件: MainPanel.java
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)));
}
 
源代码9 项目: trygve   文件: TextEditorGUI.java
public ArrayList<Integer> breakpointByteOffsets() {
	State state = State.LookingForField;
	ArrayList<Integer> retval = new ArrayList<Integer>();
	
	final StyledDocument doc = (StyledDocument)editPane.getDocument();
	final SimpleAttributeSet breakpointColored = new SimpleAttributeSet(); 
	StyleConstants.setBackground(breakpointColored, Color.cyan);
	
	for(int i = 0; i < doc.getLength(); i++) {
		final Element element = doc.getCharacterElement(i);
	    final AttributeSet set = element.getAttributes();
	    final Color backgroundColor = StyleConstants.getBackground(set);
	    switch (state) {
	    case LookingForField:
	    	if (true == backgroundColor.equals(Color.cyan)) {
	    		state = State.InField;
	    		retval.add(new Integer(i));
	    	}
	    	break;
	    case InField:
	    	if (false == backgroundColor.equals(Color.cyan)) {
	    		state = State.LookingForField;
	    	} else if (element.toString().equals("\n")) {
	    		state = State.LookingForField;
	    	}
	    	break;
	    default:
	    	assert (false);
	    	break;
	    }
	}
	
	return retval;
}
 
源代码10 项目: littleluck   文件: HTMLPanel.java
@Override
public View create(Element element) {
    AttributeSet attrs = element.getAttributes();
    Object elementName =
            attrs.getAttribute(AbstractDocument.ElementNameAttribute);
    Object o = (elementName != null) ?
            null : attrs.getAttribute(StyleConstants.NameAttribute);
    if (o instanceof HTML.Tag) {
        if (o == HTML.Tag.OBJECT) {
            return new ComponentView(element);
        }
    }
    return super.create(element);
}
 
源代码11 项目: binnavi   文件: SyntaxDocument.java
private void highlightLinesAfter(final String content, final int line) {
  final int offset = rootElement.getElement(line).getEndOffset();

  // Start/End delimiter not found, nothing to do

  int startDelimiter = indexOf(content, getStartDelimiter(), offset);
  int endDelimiter = indexOf(content, getEndDelimiter(), offset);

  if (startDelimiter < 0) {
    startDelimiter = content.length();
  }

  if (endDelimiter < 0) {
    endDelimiter = content.length();
  }

  final int delimiter = Math.min(startDelimiter, endDelimiter);

  if (delimiter < offset) {
    return;
  }

  // Start/End delimiter found, reapply highlighting

  final int endLine = rootElement.getElementIndex(delimiter);

  for (int i = line + 1; i < endLine; i++) {
    final Element branch = rootElement.getElement(i);
    final Element leaf = doc.getCharacterElement(branch.getStartOffset());
    final AttributeSet as = leaf.getAttributes();

    if (as.isEqual(comment)) {
      applyHighlighting(content, i);
    }
  }
}
 
源代码12 项目: java-swing-tips   文件: MainPanel.java
private void setElementColor(Element element, String color) {
  AttributeSet attrs = element.getAttributes();
  Object o = attrs.getAttribute(HTML.Tag.A);
  if (o instanceof MutableAttributeSet) {
    MutableAttributeSet a = (MutableAttributeSet) o;
    a.addAttribute(HTML.Attribute.COLOR, color);
  }
}
 
源代码13 项目: stendhal   文件: KTextEdit.java
@Override
public void mouseClicked(MouseEvent e) {
	StyledDocument doc = (StyledDocument) textPane.getDocument();
	Element ele = doc.getCharacterElement(textPane.viewToModel(e.getPoint()));
	AttributeSet as = ele.getAttributes();
	Object fla = as.getAttribute("linkact");
	if (fla instanceof LinkListener) {
		try {
			((LinkListener) fla).linkClicked(doc.getText(ele.getStartOffset(), ele.getEndOffset() - ele.getStartOffset()));
		} catch (BadLocationException exc) {
			logger.error("Trying to extract link from invalid range", exc);
		}
	}
}
 
源代码14 项目: PolyGlot   文件: FormattedTextHelper.java
/**
 * Recursing method implementing functionality of storageFormat()
 * @param e element to be cycled through
 * @param pane top parent JTextPane
 * @return string format value of current node and its children
 * @throws BadLocationException if unable to create string format
 */
private static String storeFormatRecurse(Element e, JTextPane pane) throws Exception {
    String ret = "";
    int ec = e.getElementCount();

    if (ec == 0) {
        // if more media addable in the future, this is where to process it...
        // hard coded values because they're hard coded in Java. Eh.
        if (e.getAttributes().getAttribute("$ename") != null
                && e.getAttributes().getAttribute("$ename").equals("icon")) {
            if (e.getAttributes().getAttribute(PGTUtil.IMAGE_ID_ATTRIBUTE) == null) {
                throw new Exception("ID For image not stored. Unable to store section.");
            }
            
            ret += "<img src=\"" + e.getAttributes().getAttribute(PGTUtil.IMAGE_ID_ATTRIBUTE) + "\">";
        } else {
            int start = e.getStartOffset();
            int len = e.getEndOffset() - start;
            if (start < pane.getDocument().getLength()) {
                AttributeSet a = e.getAttributes();
                String font = StyleConstants.getFontFamily(a);
                String fontColor = colorToText(StyleConstants.getForeground(a));
                int fontSize = StyleConstants.getFontSize(a);
                ret += "<font face=\"" + font + "\""
                        + "size=\"" + fontSize + "\""
                        + "color=\"" + fontColor + "\"" + ">";
                ret += pane.getDocument().getText(start, len);
                ret += "</font>";
            }
        }
    } else {
        for (int i = 0; i < ec; i++) {
            ret += storeFormatRecurse(e.getElement(i), pane);
        }
    }

    return ret;
}
 
源代码15 项目: wpcleaner   文件: MWPaneCheckWikiPopupListener.java
/**
 * Construct popup menu.
 * 
 * @param textPane Text pane.
 * @param position Position in text.
 * @param pageAnalysis Page analysis.
 */
@Override
protected JPopupMenu createPopup(
    MWPane textPane, int position,
    PageAnalysis pageAnalysis) {
  if ((textPane == null) || (pageAnalysis == null)) {
    return null;
  }
  Element element = textPane.getStyledDocument().getCharacterElement(position);
  if (element == null) {
    return null;
  }

  // Check if it's for Check Wiki
  AttributeSet attributes = element.getAttributes();
  Object attrInfo = attributes.getAttribute(MWPaneFormatter.ATTRIBUTE_INFO);
  if (!(attrInfo instanceof CheckErrorResult)) {
    return null;
  }

  CheckErrorResult info = (CheckErrorResult) attrInfo;
  MWPaneCheckWikiMenuCreator menu = new MWPaneCheckWikiMenuCreator();
  JPopupMenu popup = menu.createPopupMenu(null);
  menu.addInfo(popup, element, textPane, info);
  menu.addItemCopyPaste(popup, textPane);
  return popup;
}
 
源代码16 项目: SikuliX1   文件: ButtonCapture.java
private boolean replaceButton(Element src, String imgFullPath) {
  if (captureCancelled) {
    if (_codePane.showThumbs && PreferencesUser.get().getPrefMoreImageThumbs()
            || !_codePane.showThumbs) {
      return true;
    }
  }
  int start = src.getStartOffset();
  int end = src.getEndOffset();
  int old_sel_start = _codePane.getSelectionStart(),
          old_sel_end = _codePane.getSelectionEnd();
  try {
    StyledDocument doc = (StyledDocument) src.getDocument();
    String text = doc.getText(start, end - start);
    Debug.log(3, text);
    for (int i = start; i < end; i++) {
      Element elm = doc.getCharacterElement(i);
      if (elm.getName().equals(StyleConstants.ComponentElementName)) {
        AttributeSet attr = elm.getAttributes();
        Component com = StyleConstants.getComponent(attr);
        boolean isButton = com instanceof ButtonCapture;
        boolean isLabel = com instanceof EditorPatternLabel;
        if (isButton || isLabel && ((EditorPatternLabel) com).isCaptureButton()) {
          Debug.log(5, "button is at " + i);
          int oldCaretPos = _codePane.getCaretPosition();
          _codePane.select(i, i + 1);
          if (!_codePane.showThumbs) {
            _codePane.insertString((new EditorPatternLabel(_codePane, imgFullPath, true)).toString());
          } else {
            if (PreferencesUser.get().getPrefMoreImageThumbs()) {
              com = new EditorPatternButton(_codePane, imgFullPath);
            } else {
              if (captureCancelled) {
                com = new EditorPatternLabel(_codePane, "");
              } else {
                com = new EditorPatternLabel(_codePane, imgFullPath, true);
              }
            }
            _codePane.insertComponent(com);
          }
          _codePane.setCaretPosition(oldCaretPos);
          break;
        }
      }
    }
  } catch (BadLocationException ble) {
    Debug.error(me + "Problem inserting Button!\n%s", ble.getMessage());
  }
  _codePane.select(old_sel_start, old_sel_end);
  _codePane.requestFocus();
  return true;
}
 
源代码17 项目: SwingBox   文件: TextBoxView.java
/**
 * Instantiates a new text based view, able to display rich text. This view
 * corresponds to TextBox in CSSBox. <br>
 * <a href="http://www.w3.org/TR/CSS21/box.html">Box Model</a>
 * 
 * @param elem
 *            the elem
 * 
 */

public TextBoxView(Element elem)
{
    super(elem);
    AttributeSet tmpAttr = elem.getAttributes();
    Object obj = tmpAttr.getAttribute(Constants.ATTRIBUTE_BOX_REFERENCE);
    anchor = (Anchor) tmpAttr.getAttribute(Constants.ATTRIBUTE_ANCHOR_REFERENCE);
    Integer i = (Integer) tmpAttr.getAttribute(Constants.ATTRIBUTE_DRAWING_ORDER);
    order = (i == null) ? -1 : i;

    if (obj instanceof TextBox)
    {
        box = (TextBox) obj;
    }
    else
    {
        throw new IllegalArgumentException("Box reference is not an instance of TextBox");
    }
    
    if (box.getNode() != null && box.getNode().getParentNode() instanceof org.w3c.dom.Element)
    {
        org.w3c.dom.Element pelem = Anchor.findAnchorElement((org.w3c.dom.Element) box.getNode().getParentNode());
        Map<String, String> elementAttributes = anchor.getProperties();

        if (pelem != null)
        {
            anchor.setActive(true);
            elementAttributes.put(Constants.ELEMENT_A_ATTRIBUTE_HREF, pelem.getAttribute("href"));
            elementAttributes.put(Constants.ELEMENT_A_ATTRIBUTE_NAME, pelem.getAttribute("name"));
            elementAttributes.put(Constants.ELEMENT_A_ATTRIBUTE_TITLE, pelem.getAttribute("title"));
            String target = pelem.getAttribute("target");
            if ("".equals(target))
            {
                target = "_self";
            }
            elementAttributes.put(Constants.ELEMENT_A_ATTRIBUTE_TARGET, target);
            // System.err.println("## Anchor at : " + this + " attr: "+
            // elementAttributes);
        }
        else
        {
            anchor.setActive(false);
            elementAttributes.clear();
        }
    }

}
 
源代码18 项目: jdk8u_jdk   文件: ImageView.java
/**
 * Recreates and reloads the image.  This should
 * only be invoked from <code>refreshImage</code>.
 */
private void updateImageSize() {
    int newWidth = 0;
    int newHeight = 0;
    int newState = 0;
    Image newImage = getImage();

    if (newImage != null) {
        Element elem = getElement();
        AttributeSet attr = elem.getAttributes();

        // Get the width/height and set the state ivar before calling
        // anything that might cause the image to be loaded, and thus the
        // ImageHandler to be called.
        newWidth = getIntAttr(HTML.Attribute.WIDTH, -1);
        newHeight = getIntAttr(HTML.Attribute.HEIGHT, -1);

        if (newWidth > 0) {
            newState |= WIDTH_FLAG;
        }

        if (newHeight > 0) {
            newState |= HEIGHT_FLAG;
        }

        /*
        If synchronous loading flag is set, then make sure that the image is
        scaled appropriately.
        Otherwise, the ImageHandler::imageUpdate takes care of scaling the image
        appropriately.
        */
        if (getLoadsSynchronously()) {
            Image img;
            synchronized(this) {
                img = image;
            }
            int w = img.getWidth(imageObserver);
            int h = img.getHeight(imageObserver);
            if (w > 0 && h > 0) {
                Dimension d = adjustWidthHeight(w, h);
                newWidth = d.width;
                newHeight = d.height;
                newState |= (WIDTH_FLAG | HEIGHT_FLAG);
            }
        }

        // Make sure the image starts loading:
        if ((newState & (WIDTH_FLAG | HEIGHT_FLAG)) != 0) {
            Toolkit.getDefaultToolkit().prepareImage(newImage, newWidth,
                                                     newHeight,
                                                     imageObserver);
        }
        else {
            Toolkit.getDefaultToolkit().prepareImage(newImage, -1, -1,
                                                     imageObserver);
        }

        boolean createText = false;
        synchronized(this) {
            // If imageloading failed, other thread may have called
            // ImageLoader which will null out image, hence we check
            // for it.
            if (image != null) {
                if ((newState & WIDTH_FLAG) == WIDTH_FLAG || width == 0) {
                    width = newWidth;
                }
                if ((newState & HEIGHT_FLAG) == HEIGHT_FLAG ||
                    height == 0) {
                    height = newHeight;
                }
            }
            else {
                createText = true;
                if ((newState & WIDTH_FLAG) == WIDTH_FLAG) {
                    width = newWidth;
                }
                if ((newState & HEIGHT_FLAG) == HEIGHT_FLAG) {
                    height = newHeight;
                }
            }
            state = state | newState;
            state = (state | LOADING_FLAG) ^ LOADING_FLAG;
        }
        if (createText) {
            // Only reset if this thread determined image is null
            updateAltTextView();
        }
    }
    else {
        width = height = DEFAULT_HEIGHT;
        updateAltTextView();
    }
}
 
源代码19 项目: SwingBox   文件: BackgroundView.java
/**
 * 
 */
public BackgroundView(Element elem)
{
    super(elem);
    AttributeSet tmpAttr = elem.getAttributes();
    Object obj = tmpAttr.getAttribute(Constants.ATTRIBUTE_BOX_REFERENCE);
    anchor = (Anchor) tmpAttr.getAttribute(Constants.ATTRIBUTE_ANCHOR_REFERENCE);
    Integer i = (Integer) tmpAttr.getAttribute(Constants.ATTRIBUTE_DRAWING_ORDER);
    order = (i == null) ? -1 : i;

    if (obj instanceof ElementBox)
    {
        box = (ElementBox) obj;
    }
    else
    {
        throw new IllegalArgumentException("Box reference is not an instance of ElementBox");
    }
    
    if (box.toString().contains("\"btn\""))
        System.out.println("jo!");
    
    if (box.getElement() != null)
    {
        Map<String, String> elementAttributes = anchor.getProperties();
        org.w3c.dom.Element pelem = Anchor.findAnchorElement(box.getElement());
        if (pelem != null)
        {
            anchor.setActive(true);
            elementAttributes.put(Constants.ELEMENT_A_ATTRIBUTE_HREF, pelem.getAttribute("href"));
            elementAttributes.put(Constants.ELEMENT_A_ATTRIBUTE_NAME, pelem.getAttribute("name"));
            elementAttributes.put(Constants.ELEMENT_A_ATTRIBUTE_TITLE, pelem.getAttribute("title"));
            String target = pelem.getAttribute("target");
            if ("".equals(target))
            {
                target = "_self";
            }
            elementAttributes.put(Constants.ELEMENT_A_ATTRIBUTE_TARGET, target);
        }
        else
        {
            anchor.setActive(false);
            elementAttributes.clear();
        }
    }
    
}
 
源代码20 项目: wpcleaner   文件: MWPaneReplaceAllAction.java
/**
 * @param e Event.
 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
 */
@Override
public void actionPerformed(ActionEvent e) {
  MWPane textPane = getMWPane(e);
  if (textPane == null) {
    return;
  }
  StyledDocument doc = textPane.getStyledDocument();
  if (doc == null) {
    return;
  }
  int length = doc.getLength();
  int lastEnd = Integer.MAX_VALUE;
  for (int pos = 0; pos < length; pos = lastEnd) {
    try {
      Element run = doc.getCharacterElement(pos);
      lastEnd = run.getEndOffset();
      if (pos == lastEnd) {
        // offset + length beyond length of document, bail.
        break;
      }
      MutableAttributeSet attr = (MutableAttributeSet) run.getAttributes();
      if ((attr != null) &&
          (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_TYPE) != null) &&
          (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_INFO) != null)) {
        Object attrInfo = attr.getAttribute(MWPaneFormatter.ATTRIBUTE_INFO);
        if (attrInfo instanceof CheckErrorResult) {
          int startOffset = MWPaneFormatter.getUUIDStartOffset(textPane, run);
          int endOffset = MWPaneFormatter.getUUIDEndOffet(textPane, run);
          if (originalText.equals(textPane.getText(startOffset, endOffset - startOffset))) {
            boolean possible = false;
            CheckErrorResult info = (CheckErrorResult) attrInfo;
            List<Actionnable> actionnables = info.getPossibleActions();
            if (actionnables != null) {
              for (Actionnable actionnable : actionnables) {
                possible |= actionnable.isPossibleReplacement(newText);
              }
            }
            if (possible) {
              doc.remove(startOffset, endOffset - startOffset);
              doc.insertString(startOffset, newText, attr);
              lastEnd = startOffset + newText.length();
            }
          }
        }
      }
    } catch (BadLocationException exception) {
      // Nothing to do
    }
  }
}