Java Code Examples for javax.swing.text.AttributeSet#getAttribute()

The following examples show how to use javax.swing.text.AttributeSet#getAttribute() . 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: BraceMatchingSidebarComponent.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void updateColors(final FontColorSettings fcs) {
    if (getParent() == null) {
        return;
    }
    AttributeSet as = fcs.getFontColors(BRACES_COLORING);
    if (as == null) {
        as = fcs.getFontColors(FontColorNames.DEFAULT_COLORING);
        this.backColor = (Color)as.getAttribute(StyleConstants.ColorConstants.Background);
    } else {
        this.backColor = (Color)as.getAttribute(StyleConstants.ColorConstants.Background);
        as = AttributesUtilities.createComposite(
                as, 
                fcs.getFontColors(FontColorNames.DEFAULT_COLORING));
    }
    this.coloring = Coloring.fromAttributeSet(as);
    int w = 0;
    
    if (coloring.getFont() != null) {
        w = coloring.getFont().getSize();
    } else if (baseUI != null) {
        w = baseUI.getEditorUI().getLineNumberDigitWidth();
    }
    this.barWidth = Math.max(4, w / 2);
    updatePreferredSize();
}
 
Example 2
Source File: FSwingHtml.java    From pra with MIT License 6 votes vote down vote up
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;
	}
 
Example 3
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override public ViewFactory getViewFactory() {
  return new HTMLFactory() {
    @Override public View create(Element elem) {
      AttributeSet attrs = elem.getAttributes();
      Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
      Object o = Objects.isNull(elementName) ? attrs.getAttribute(StyleConstants.NameAttribute) : null;
      if (o instanceof HTML.Tag) {
        HTML.Tag kind = (HTML.Tag) o;
        if (kind == HTML.Tag.DIV) {
          return new BlockView(elem, View.Y_AXIS) {
            @Override public String getToolTipText(float x, float y, Shape allocation) {
              String s = super.getToolTipText(x, y, allocation);
              if (Objects.isNull(s)) {
                s = Objects.toString(getElement().getAttributes().getAttribute(HTML.Attribute.TITLE));
              }
              return s;
            }
          };
        }
      }
      return super.create(elem);
    }
  };
}
 
Example 4
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 5
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
protected void checkId(Element element) {
  AttributeSet attrs = element.getAttributes();
  Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
  Object name = Objects.isNull(elementName) ? attrs.getAttribute(StyleConstants.NameAttribute) : null;
  HTML.Tag tag;
  if (name instanceof HTML.Tag) {
    tag = (HTML.Tag) name;
  } else {
    return;
  }
  textArea.append(String.format("%s%n", tag));
  if (tag.isBlock()) { // block
    Object bid = attrs.getAttribute(HTML.Attribute.ID);
    if (Objects.nonNull(bid)) {
      textArea.append(String.format("block: id=%s%n", bid));
      addHighlight(element, true);
    }
  } else { // inline
    Enumeration<?> e = attrs.getAttributeNames();
    while (e.hasMoreElements()) {
      Object obj = attrs.getAttribute(e.nextElement());
      // System.out.println("AttributeNames: " + obj);
      if (obj instanceof AttributeSet) {
        AttributeSet a = (AttributeSet) obj;
        Object iid = a.getAttribute(HTML.Attribute.ID);
        if (Objects.nonNull(iid)) {
          textArea.append(String.format("inline: id=%s%n", iid));
          addHighlight(element, false);
        }
      }
    }
  }
}
 
Example 6
Source File: MergingOffsetsBagTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void assertAttribs(String msg, AttributeSet as, String... keys) {
    assertEquals(msg, keys.length, as.getAttributeCount());
    for (String key : keys) {
        if (null == as.getAttribute(key)) {
            fail(msg + " attribute key: " + key);
        }
    }
}
 
Example 7
Source File: EmbeddingHighlightsContainer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Color getColoring(FontColorSettings fcs, String tokenName) {
    AttributeSet as = fcs.getTokenFontColors(tokenName);
    if (as != null) {
        return (Color) as.getAttribute(StyleConstants.Background); //NOI18N
    }
    return null;
}
 
Example 8
Source File: HTML.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches an integer attribute value.  Attribute values
 * are stored as a string, and this is a convenience method
 * to convert to an actual integer.
 *
 * @param attr the set of attributes to use to try to fetch a value
 * @param key the key to use to fetch the value
 * @param def the default value to use if the attribute isn't
 *  defined or there is an error converting to an integer
 */
public static int getIntegerAttributeValue(AttributeSet attr,
                                           Attribute key, int def) {
    int value = def;
    String istr = (String) attr.getAttribute(key);
    if (istr != null) {
        try {
            value = Integer.valueOf(istr).intValue();
        } catch (NumberFormatException e) {
            value = def;
        }
    }
    return value;
}
 
Example 9
Source File: HTMLPanel.java    From littleluck with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 10
Source File: AttributesUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public boolean containsAttributes(AttributeSet attributes) {
    for(Enumeration<?> keys = attributes.getAttributeNames(); keys.hasMoreElements(); ) {
        Object key = keys.nextElement();
        Object value = attributes.getAttribute(key);

        if (!containsAttribute(key, value)) {
            return false;
        }
    }

    return true;
}
 
Example 11
Source File: ReporterResultTopComponent.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void hyperlinkUpdate(final HyperlinkEvent e) {
    if (!HyperlinkEvent.EventType.ACTIVATED.equals(e.getEventType())) {
        return;
    }
    BugTrackingAccessor accessor = Lookup.getDefault().lookup(BugTrackingAccessor.class);
    if (accessor != null){
        AttributeSet ats = e.getSourceElement().getAttributes();
        Object attribute = ats.getAttribute(HTML.getTag("a"));
        if (attribute instanceof SimpleAttributeSet) {
            SimpleAttributeSet attributeSet = (SimpleAttributeSet) attribute;
            Object bugId = attributeSet.getAttribute(HTML.getAttributeKey("id"));
            if (bugId != null){
                try{
                    Integer.parseInt(bugId.toString());
                    LOG.log(Level.FINE, "Open issue {0}", bugId);
                    accessor.openIssue(bugId.toString());
                    return;
                }catch(NumberFormatException nfe){
                    LOG.log(Level.INFO, "Invalid id attribute", nfe);
                }
            }
        }
    } else {
        LOG.log(Level.INFO, "Bugzilla Accessor not found");
    }
    RP.post(new Runnable(){

        @Override
        public void run() {
            HtmlBrowser.URLDisplayer.getDefault().showURL(e.getURL());
        }

    });
}
 
Example 12
Source File: Map.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates and returns an instance of RegionContainment that can be
 * used to test if a particular point lies inside a region.
 */
protected RegionContainment createRegionContainment
                              (AttributeSet attributes) {
    Object     shape = attributes.getAttribute(HTML.Attribute.SHAPE);

    if (shape == null) {
        shape = "rect";
    }
    if (shape instanceof String) {
        String                shapeString = ((String)shape).toLowerCase();
        RegionContainment     rc = null;

        try {
            if (shapeString.equals("rect")) {
                rc = new RectangleRegionContainment(attributes);
            }
            else if (shapeString.equals("circle")) {
                rc = new CircleRegionContainment(attributes);
            }
            else if (shapeString.equals("poly")) {
                rc = new PolygonRegionContainment(attributes);
            }
            else if (shapeString.equals("default")) {
                rc = DefaultRegionContainment.sharedInstance();
            }
        } catch (RuntimeException re) {
            // Something wrong with attributes.
            rc = null;
        }
        return rc;
    }
    return null;
}
 
Example 13
Source File: HTML.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fetches an integer attribute value.  Attribute values
 * are stored as a string, and this is a convenience method
 * to convert to an actual integer.
 *
 * @param attr the set of attributes to use to try to fetch a value
 * @param key the key to use to fetch the value
 * @param def the default value to use if the attribute isn't
 *  defined or there is an error converting to an integer
 */
public static int getIntegerAttributeValue(AttributeSet attr,
                                           Attribute key, int def) {
    int value = def;
    String istr = (String) attr.getAttribute(key);
    if (istr != null) {
        try {
            value = Integer.valueOf(istr).intValue();
        } catch (NumberFormatException e) {
            value = def;
        }
    }
    return value;
}
 
Example 14
Source File: CSS.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the length of the attribute in <code>a</code> with
 * key <code>key</code>.
 */
float getLength(AttributeSet a, CSS.Attribute key, StyleSheet ss) {
    ss = getStyleSheet(ss);
    LengthValue lv = (LengthValue) a.getAttribute(key);
    boolean isW3CLengthUnits = (ss == null) ? false : ss.isW3CLengthUnits();
    float len = (lv != null) ? lv.getValue(isW3CLengthUnits) : 0;
    return len;
}
 
Example 15
Source File: ColorModel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void setAnnotations (
String profile, 
Collection<AttributeSet> annotations
   ) {
if (annotations == null) {
           EditorSettings.getDefault().setAnnotations(profile, null);
           return;
       }      
       Collection<AttributeSet> annos = new ArrayList<AttributeSet>();
for(AttributeSet category : annotations) {
    AnnotationType annotationType = (AnnotationType) 
	category.getAttribute ("annotationType");
           
           SimpleAttributeSet c = new SimpleAttributeSet();
           c.addAttribute(StyleConstants.NameAttribute, category.getAttribute(StyleConstants.NameAttribute));
    if (category.isDefined (StyleConstants.Background)) {
	annotationType.setUseHighlightColor (true);
               if (annotationType.getHighlight() == null || !annotationType.getHighlight().equals((Color) category.getAttribute (StyleConstants.Background))) {
                   annotationType.setHighlight (
                       (Color) category.getAttribute (StyleConstants.Background)
                   );
               }
               c.addAttribute(StyleConstants.Background, category.getAttribute(StyleConstants.Background));
           } else
	annotationType.setUseHighlightColor (false);
    if (category.isDefined (StyleConstants.Foreground)) {
	annotationType.setInheritForegroundColor (false);
               if (annotationType.getForegroundColor() == null || !annotationType.getForegroundColor().equals( (Color) category.getAttribute (StyleConstants.Foreground))) {
                   annotationType.setForegroundColor (
                   (Color) category.getAttribute (StyleConstants.Foreground)
                   );
               }
               c.addAttribute(StyleConstants.Foreground, category.getAttribute(StyleConstants.Foreground));
           } else
	annotationType.setInheritForegroundColor (true);
    if (category.isDefined (EditorStyleConstants.WaveUnderlineColor)) {     
               annotationType.setUseWaveUnderlineColor (true);
               if(category.getAttribute (EditorStyleConstants.WaveUnderlineColor) == null || !category.getAttribute (EditorStyleConstants.WaveUnderlineColor).equals(annotationType.getWaveUnderlineColor())) {
                   annotationType.setWaveUnderlineColor (
                       (Color) category.getAttribute (EditorStyleConstants.WaveUnderlineColor)
                   );
               }
               c.addAttribute((EditorStyleConstants.WaveUnderlineColor), category.getAttribute (EditorStyleConstants.WaveUnderlineColor));
           } else
               annotationType.setUseWaveUnderlineColor (false);
    //S ystem.out.println("  " + category.getDisplayName () + " : " + annotationType + " : " + annotationType.getHighlight() + " : " + annotationType.isUseHighlightColor());
           annos.add(c);
}
       
       EditorSettings.getDefault().setAnnotations(profile, toMap(annos));
   }
 
Example 16
Source File: AnnotationsPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void refreshUI () {
    int index = lCategories.getSelectedIndex ();
    if (index < 0) {
 // no category selected
        cbForeground.setEnabled (false);
        cbBackground.setEnabled (false);
        cbEffectColor.setEnabled (false);
        return;
    }
    cbForeground.setEnabled (true);
    cbBackground.setEnabled (true);
    cbEffectColor.setEnabled (true);
    
    listen = false;
    
    // set defaults
    AttributeSet defAs = getDefaultColoring();
    if (defAs != null) {
        Color inheritedForeground = (Color) defAs.getAttribute(StyleConstants.Foreground);
        if (inheritedForeground == null) {
            inheritedForeground = Color.black;
        }
        ColorComboBoxSupport.setInheritedColor((ColorComboBox)cbForeground, inheritedForeground);
        
        Color inheritedBackground = (Color) defAs.getAttribute(StyleConstants.Background);
        if (inheritedBackground == null) {
            inheritedBackground = Color.white;
        }
        ColorComboBoxSupport.setInheritedColor((ColorComboBox)cbBackground, inheritedBackground);
    }

    // set values
    List<AttributeSet> annotations = getAnnotations (currentScheme);
    AttributeSet c = annotations.get (index);
    ColorComboBoxSupport.setSelectedColor( (ColorComboBox)cbForeground, (Color) c.getAttribute (StyleConstants.Foreground));
    ColorComboBoxSupport.setSelectedColor( (ColorComboBox)cbBackground, (Color) c.getAttribute (StyleConstants.Background));
    if (c.getAttribute(EditorStyleConstants.WaveUnderlineColor) != null) {
        cbEffects.setSelectedIndex(1);
        cbEffectColor.setEnabled(true);
        ((ColorComboBox)cbEffectColor).setSelectedColor((Color) c.getAttribute (EditorStyleConstants.WaveUnderlineColor));
    } else {
        cbEffects.setSelectedIndex(0);
        cbEffectColor.setEnabled(false);
        cbEffectColor.setSelectedIndex(-1);
    } 
    listen = true;
}
 
Example 17
Source File: HighlightingPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void refreshUI () {
       int index = lCategories.getSelectedIndex ();
       if (index < 0) {
           cbForeground.setEnabled (false);
           cbBackground.setEnabled (false);
           return;
       }
       cbForeground.setEnabled (true);
       cbBackground.setEnabled (true);
       
       List<AttributeSet> categories = getCategories (currentProfile);
AttributeSet category = categories.get (index);
       
       listen = false;
       
       // set defaults
       AttributeSet defAs = getDefaultColoring();
       if (defAs != null) {
           Color inheritedForeground = (Color) defAs.getAttribute(StyleConstants.Foreground);
           if (inheritedForeground == null) {
               inheritedForeground = Color.black;
           }
           ColorComboBoxSupport.setInheritedColor((ColorComboBox)cbForeground, inheritedForeground);
           
           Color inheritedBackground = (Color) defAs.getAttribute(StyleConstants.Background);
           if (inheritedBackground == null) {
               inheritedBackground = Color.white;
           }
           ColorComboBoxSupport.setInheritedColor((ColorComboBox)cbBackground, inheritedBackground);
       }

       if (category.getAttribute(StyleConstants.Underline) != null) {
           cbEffects.setSelectedIndex(1);
           cbEffectColor.setEnabled(true);
           ((ColorComboBox) cbEffectColor).setSelectedColor((Color) category.getAttribute(StyleConstants.Underline));
       } else if (category.getAttribute(EditorStyleConstants.WaveUnderlineColor) != null) {
           cbEffects.setSelectedIndex(2);
           cbEffectColor.setEnabled(true);
           ((ColorComboBox) cbEffectColor).setSelectedColor((Color) category.getAttribute(EditorStyleConstants.WaveUnderlineColor));
       } else if (category.getAttribute(StyleConstants.StrikeThrough) != null) {
           cbEffects.setSelectedIndex(3);
           cbEffectColor.setEnabled(true);
           ((ColorComboBox) cbEffectColor).setSelectedColor((Color) category.getAttribute(StyleConstants.StrikeThrough));
       } else {
           cbEffects.setSelectedIndex(0);
           cbEffectColor.setEnabled(false);
           cbEffectColor.setSelectedIndex(-1);
       }
   
       // set values
       ColorComboBoxSupport.setSelectedColor((ColorComboBox)cbForeground, (Color) category.getAttribute (StyleConstants.Foreground));
       ColorComboBoxSupport.setSelectedColor((ColorComboBox)cbBackground, (Color) category.getAttribute (StyleConstants.Background));
       listen = true;
   }
 
Example 18
Source File: RTFHTMLHandler.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public void startElement( String name, AttributeSet attributeSet )
{
	this.currentNode = new HTMLNode( ).name( name.equalsIgnoreCase( "paragraph" ) ? "div"
			: name );
	this.currentNode.parent( this.parentNode );
	this.nodeStack.add( this.currentNode );
	this.parentNode = this.currentNode;

	Object fontfamily = attributeSet.getAttribute( StyleConstants.FontFamily );
	Object fontsize = attributeSet.getAttribute( StyleConstants.FontSize );
	Object fontcolor = attributeSet.getAttribute( StyleConstants.Foreground );
	if ( fontfamily != null || fontsize != null || fontcolor != null )
	{
		HTMLNode fontnode = new HTMLNode( ).name( "font" );
		if ( fontfamily != null )
			fontnode.attribute( "face", fontfamily.toString( ) );
		if ( fontcolor != null )
		{
			Color color = (Color) fontcolor;
			fontnode.attribute( "color", makeColorString( color ) );
		}
		if ( fontsize != null )
		{
			int size = ( (Integer) fontsize ).intValue( );
			fontnode.attribute( "size", size / 4 + "" );
		}
		this.currentNode = this.currentNode.child( fontnode );
	}
	Object italic = attributeSet.getAttribute( StyleConstants.Italic );
	if ( italic != null && ( (Boolean) italic ).booleanValue( ) )
	{
		this.currentNode = this.currentNode.child( new HTMLNode( ).name( "i" ) );
	}
	Object underline = attributeSet.getAttribute( StyleConstants.Underline );
	if ( underline != null && ( (Boolean) underline ).booleanValue( ) )
	{
		this.currentNode = this.currentNode.child( new HTMLNode( ).name( "u" ) );
	}
	Object bold = attributeSet.getAttribute( StyleConstants.Bold );
	if ( bold != null && ( (Boolean) bold ).booleanValue( ) )
	{
		this.currentNode = this.currentNode.child( new HTMLNode( ).name( "b" ) );
	}
}
 
Example 19
Source File: HighlightsViewUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static Color foreColor(AttributeSet attrs) {
    return (attrs != null)
            ? (Color) attrs.getAttribute(StyleConstants.Foreground)
            : null;
}
 
Example 20
Source File: CSS.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the font for the values in the passed in AttributeSet.
 * It is assumed the keys will be CSS.Attribute keys.
 * <code>sc</code> is the StyleContext that will be messaged to get
 * the font once the size, name and style have been determined.
 */
Font getFont(StyleContext sc, AttributeSet a, int defaultSize, StyleSheet ss) {
    ss = getStyleSheet(ss);
    int size = getFontSize(a, defaultSize, ss);

    /*
     * If the vertical alignment is set to either superscript or
     * subscript we reduce the font size by 2 points.
     */
    StringValue vAlignV = (StringValue)a.getAttribute
                          (CSS.Attribute.VERTICAL_ALIGN);
    if ((vAlignV != null)) {
        String vAlign = vAlignV.toString();
        if ((vAlign.indexOf("sup") >= 0) ||
            (vAlign.indexOf("sub") >= 0)) {
            size -= 2;
        }
    }

    FontFamily familyValue = (FontFamily)a.getAttribute
                                        (CSS.Attribute.FONT_FAMILY);
    String family = (familyValue != null) ? familyValue.getValue() :
                              Font.SANS_SERIF;
    int style = Font.PLAIN;
    FontWeight weightValue = (FontWeight) a.getAttribute
                              (CSS.Attribute.FONT_WEIGHT);
    if ((weightValue != null) && (weightValue.getValue() > 400)) {
        style |= Font.BOLD;
    }
    Object fs = a.getAttribute(CSS.Attribute.FONT_STYLE);
    if ((fs != null) && (fs.toString().indexOf("italic") >= 0)) {
        style |= Font.ITALIC;
    }
    if (family.equalsIgnoreCase("monospace")) {
        family = Font.MONOSPACED;
    }
    Font f = sc.getFont(family, style, size);
    if (f == null
        || (f.getFamily().equals(Font.DIALOG)
            && ! family.equalsIgnoreCase(Font.DIALOG))) {
        family = Font.SANS_SERIF;
        f = sc.getFont(family, style, size);
    }
    return f;
}