APIdia Launch Partner
Top Description Inners Fields Constructors Methods
javax.swing.text.html

public Class StyleSheet

extends StyleContext
Class Inheritance
Known Direct Subclasses
javax.swing.plaf.basic.BasicEditorPaneUI.StyleSheetUIResource
Annotations
@SuppressWarnings:serial
Imports
java.awt.Color, .Component, .Container, .Font, .FontMetrics, .Graphics, .Graphics2D, .Insets, .Rectangle, .RenderingHints, .Shape, java.io.BufferedReader, .IOException, .InputStream, .InputStreamReader, .Reader, .Serializable, .StringReader, java.net.MalformedURLException, .URL, java.util.EmptyStackException, .Enumeration, .HashMap, .HashSet, .Hashtable, .Stack, .StringTokenizer, .Vector, javax.swing.Icon, .ImageIcon, .UIManager, javax.swing.border.BevelBorder, .Border, javax.swing.event.ChangeListener, javax.swing.text.AttributeSet, .Document, .Element, .MutableAttributeSet, .SimpleAttributeSet, .Style, .StyleConstants, .StyleContext, .StyledDocument, .View, sun.swing.SwingUtilities2

Support for defining the visual characteristics of HTML views being rendered. The StyleSheet is used to translate the HTML model into visual characteristics. This enables views to be customized by a look-and-feel, multiple views over the same model can be rendered differently, etc. This can be thought of as a CSS rule repository. The key for CSS attributes is an object of type CSS.Attribute. The type of the value is up to the StyleSheet implementation, but the toString method is required to return a string representation of CSS value.

The primary entry point for HTML View implementations to get their attributes is the getViewAttributes method. This should be implemented to establish the desired policy used to associate attributes with the view. Each HTMLEditorKit (i.e. and therefore each associated JEditorPane) can have its own StyleSheet, but by default one sheet will be shared by all of the HTMLEditorKit instances. HTMLDocument instance can also have a StyleSheet, which holds the document-specific CSS specifications.

In order for Views to store less state and therefore be more lightweight, the StyleSheet can act as a factory for painters that handle some of the rendering tasks. This allows implementations to determine what they want to cache and have the sharing potentially at the level that a selector is common to multiple views. Since the StyleSheet may be used by views over multiple documents and typically the HTML attributes don't effect the selector being used, the potential for sharing is significant.

The rules are stored as named styles, and other information is stored to translate the context of an element to a rule quickly. The following code fragment will display the named styles, and therefore the CSS rules contained.


 
  import java.util.*;
  import javax.swing.text.*;
  import javax.swing.text.html.*;
 
  public class ShowStyles {
 
      public static void main(String[] args) {
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
        StyleSheet styles = doc.getStyleSheet();
 
        Enumeration rules = styles.getStyleNames();
        while (rules.hasMoreElements()) {
            String name = (String) rules.nextElement();
            Style rule = styles.getStyle(name);
            System.out.println(rule.toString());
        }
        System.exit(0);
      }
  }
 

The semantics for when a CSS style should override visual attributes defined by an element are not well defined. For example, the html <body bgcolor=red> makes the body have a red background. But if the html file also contains the CSS rule body { background: blue } it becomes less clear as to what color the background of the body should be. The current implementation gives visual attributes defined in the element the highest precedence, that is they are always checked before any styles. Therefore, in the previous example the background would have a red color as the body element defines the background color to be red.

As already mentioned this supports CSS. We don't support the full CSS spec. Refer to the javadoc of the CSS class to see what properties we support. The two major CSS parsing related concepts we do not currently support are pseudo selectors, such as A:link { color: red }, and the important modifier.

Implementation Note

This implementation is currently incomplete. It can be replaced with alternative implementations that are complete. Future versions of this class will provide better CSS support.

Authors
Timothy Prinzing, Sunita Mani, Sara Swanson, Jill Nakata

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
StyleSheet.BackgroundImagePainter

Paints the background image.

public static class
StyleSheet.BoxPainter

Class to carry out some of the duties of CSS formatting.

pack-priv class
StyleSheet.CssParser

Default parser for CSS specifications that get loaded into the StyleSheet.

pack-priv class
StyleSheet.LargeConversionSet

Large set of attributes that does conversion of requests for attributes of type StyleConstants.

public static class
StyleSheet.ListPainter

Class to carry out some of the duties of CSS list formatting.

pack-priv static class
StyleSheet.ResolvedStyle

A subclass of MuxingAttributeSet that implements Style.

private static class
StyleSheet.SearchBuffer

A temporary class used to hold a Vector, a StringBuffer and a Hashtable.

pack-priv static class
StyleSheet.SelectorMapping

SelectorMapping contains a specifitiy, as an integer, and an associated Style.

pack-priv class
StyleSheet.SmallConversionSet

Small set of attributes that does conversion of requests for attributes of type StyleConstants.

pack-priv class
StyleSheet.ViewAttributeSet

A subclass of MuxingAttributeSet that translates between CSS and HTML and StyleConstants.

Field Summary

Modifier and TypeField and Description
private URL
base

Where the style sheet was found.

private CSS
private transient Object
private Vector<StyleSheet>
linkedStyleSheets

Vector of StyleSheets that the rules are to reference.

private Hashtable<String, StyleSheet.ResolvedStyle>
resolvedStyles

Maps from selector (as a string) to Style that includes all relevant styles.

private StyleSheet.SelectorMapping
selectorMapping

An inverted graph of the selectors.

private int[]
pack-priv static final int[]
sizeMapDefault

The HTML/CSS size model has seven slots that one can assign sizes to.

private boolean
Inherited from javax.swing.text.StyleContext:
DEFAULT_STYLE

Constructor Summary

AccessConstructor and Description
public
StyleSheet()

Construct a StyleSheet

Method Summary

Modifier and TypeMethod and Description
private String
_cleanSelectorString(String selector)

Returns a new String that contains only one space between non white space characters.

public AttributeSet

Returns:

the updated attribute set
addAttribute
(AttributeSet
the old attribute set
old
,
Object
the non-null attribute key
key
,
Object
the attribute value
value
)

Overrides javax.swing.text.StyleContext.addAttribute.

Implements javax.swing.text.AbstractDocument.AttributeContext.addAttribute.

Adds an attribute to the given set, and returns the new representative set.

public AttributeSet

Returns:

the updated attribute set
addAttributes
(AttributeSet
the old attribute set
old
,
AttributeSet
the attributes to add
attr
)

Overrides javax.swing.text.StyleContext.addAttributes.

Implements javax.swing.text.AbstractDocument.AttributeContext.addAttributes.

Adds a set of attributes to the element.

public void
addCSSAttribute(MutableAttributeSet
a set of attributes
attr
,
CSS.Attribute
a CSS property
key
,
String
an HTML attribute value
value
)

Adds a CSS attribute to the given set.

public boolean

Returns:

true if an HTML attribute value can be converted to a CSS attribute, false otherwise.
addCSSAttributeFromHTML
(MutableAttributeSet
a set of attributes
attr
,
CSS.Attribute
a CSS property
key
,
String
an HTML attribute value
value
)

Adds a CSS attribute to the given set.

public void
addRule(String
a set of rules
rule
)

Adds a set of rules to the sheet.

pack-priv void
addRule(String[]
the selector to use for the rule. This will be a set of simple selectors, and must be a length of 1 or greater.
selector
,
AttributeSet
the set of CSS attributes that make up the rule.
declaration
,
boolean isLinked)

Adds a rule into the StyleSheet.

private void
addSortedStyle(StyleSheet.SelectorMapping mapping, Vector<StyleSheet.SelectorMapping> elements)

Adds mapping to elements.

public void
addStyleSheet(StyleSheet
a StyleSheet
ss
)

Adds the rules from the StyleSheet ss to those of the receiver.

pack-priv String
cleanSelectorString(String selector)

Returns a string that only has one space between simple selectors, which may be the passed in String.

pack-priv AttributeSet
convertAttributeSet(AttributeSet a)

Converts a set of attributes (if necessary) so that any attributes that were specified as StyleConstants attributes and have a CSS mapping, will be converted to CSS attributes.

protected MutableAttributeSet
createLargeAttributeSet(AttributeSet
The set of attributes to be represented in the larger form.
a
)

Overrides javax.swing.text.StyleContext.createLargeAttributeSet.

Creates a large set of attributes that should trade off space for time.

private synchronized Style
createResolvedStyle(String selector, String[] tags, String[] ids, String[] classes)

Creates and returns a Style containing all the rules that match selector.

private Style
createResolvedStyle(String selector, Vector<Element>
a Vector of all the Elements the style is being asked for. The first Element is the deepest Element, with the last Element representing the root.
elements
,
HTML.Tag
the Tag to use for the first Element in elements
t
)

Creates and returns a Style containing all the rules that matches selector.

private Style
createResolvedStyle(String selector)

Creates and returns a Style containing all the rules that match selector.

protected StyleContext.SmallAttributeSet
createSmallAttributeSet(AttributeSet
The set of attributes to be represented in the compact form.
a
)

Overrides javax.swing.text.StyleContext.createSmallAttributeSet.

Creates a compact set of attributes that might be shared.

private Object
fontSizeInherit()

Proxy value to compute inherited font-size.

public Color

Returns:

the color
getBackground
(AttributeSet
the set of attributes
a
)

Overrides javax.swing.text.StyleContext.getBackground.

Takes a set of attributes and turn it into a background color specification.

pack-priv ImageIcon
getBackgroundImage(AttributeSet attr)

Returns the ImageIcon to draw in the background for attr.

public URL

Returns:

the base.
getBase
()

Returns the base.

public StyleSheet.BoxPainter

Returns:

the box formatter.
getBoxPainter
(AttributeSet
a set of CSS attributes
a
)

Fetches the box formatter to use for the given set of CSS attributes.

public AttributeSet

Returns:

a set of attributes that represents the CSS declaration.
getDeclaration
(String
a CSS declaration
decl
)

Translates a CSS declaration to an AttributeSet that represents the CSS declaration.

public Font
getFont(AttributeSet a)

Overrides javax.swing.text.StyleContext.getFont.

Fetches the font to use for the given set of attributes.

public Color

Returns:

the color
getForeground
(AttributeSet
the set of attributes
a
)

Overrides javax.swing.text.StyleContext.getForeground.

Takes a set of attributes and turn it into a foreground color specification.

public static int

Returns:

the index of HTML/CSS size model.
getIndexOfSize
(float
a size of point
pt
)

Returns the index of HTML/CSS size model.

private Style
getLinkedStyle(Style localStyle)

Returns the style that linked attributes should be added to.

public StyleSheet.ListPainter

Returns:

the list formatter.
getListPainter
(AttributeSet
a set of CSS attributes
a
)

Fetches the list formatter to use for the given set of CSS attributes.

public float

Returns:

the point size value.
getPointSize
(int
a size index
index
)

Returns the point size, given a size index.

public float

Returns:

the point size value.
getPointSize
(String
a CSS string describing font size
size
)

Given a string such as "+2", "-2", or "2", returns a point size value.

private synchronized Style
getResolvedStyle(String selector, Vector<Element> elements, HTML.Tag t)

Returns the resolved style for selector.

private synchronized Style
getResolvedStyle(String selector)

Returns the resolved style for selector.

private StyleSheet.SelectorMapping
getRootSelectorMapping()

Returns the root selector mapping that all selectors are relative to.

public Style

Returns:

the set of CSS attributes to use to render the tag
getRule
(HTML.Tag
the type to translate to visual attributes
t
,
Element
the element representing the tag; the element can be used to determine the nesting for situations where the attributes will differ if nested inside of other elements
e
)

Fetches the style to use to render the given type of HTML tag.

public Style

Returns:

the rule that best matches the selector.
getRule
(String
a space separated String of the element names.
selector
)

Fetches the rule that best matches the selector given in string form.

pack-priv String[]
getSimpleSelectors(String selector)

Returns the simple selectors that comprise selector.

pack-priv int[]
pack-priv static int
getSpecificity(String selector)

Returns the specificity of the passed in String.

private synchronized void
getStyles(StyleSheet.SelectorMapping parentMapping, Vector<StyleSheet.SelectorMapping> styles, String[] tags, String[] ids, String[] classes, int index, int numElements, HashSet<StyleSheet.SelectorMapping> alreadyChecked)

Adds parentMapping to styles, and recursively calls this method if parentMapping has any child mappings for any of the Elements in elements.

public StyleSheet[]

Returns:

an array of StyleSheets.
getStyleSheets
()

Returns an array of the linked StyleSheets.

public AttributeSet

Returns:

the of attributes
getViewAttributes
(View
a view
v
)

Fetches a set of attributes to use in the view for displaying.

public void
importStyleSheet(URL
an url
url
)

Imports a style sheet from url.

pack-priv boolean
private synchronized void
linkStyleSheetAt(StyleSheet ss, int index)

Updates the attributes of the rules to reference any related rules in ss.

public void
loadRules(Reader
the stream to read the CSS grammar from
in
,
URL
the reference URL. This value represents the location of the stream and may be null. All relative URLs specified in the stream will be based upon this parameter.
ref
)

Loads a set of rules that have been specified in terms of CSS1 grammar.

pack-priv void
rebaseSizeMap(int base)

private synchronized void
refreshResolvedRules(String selectorName, String[] selector, Style newStyle, int specificity)

Should be invoked when a new rule is added that did not previously exist.

public AttributeSet

Returns:

the updated attribute set
removeAttribute
(AttributeSet
the old set of attributes
old
,
Object
the non-null attribute name
key
)

Overrides javax.swing.text.StyleContext.removeAttribute.

Implements javax.swing.text.AbstractDocument.AttributeContext.removeAttribute.

Removes an attribute from the set.

public AttributeSet

Returns:

the updated attribute set
removeAttributes
(AttributeSet
the old attribute set
old
,
Enumeration<?>
the attribute names
names
)

Overrides javax.swing.text.StyleContext.removeAttributes.

Implements javax.swing.text.AbstractDocument.AttributeContext.removeAttributes.

Removes a set of attributes for the element.

public AttributeSet

Returns:

the updated attribute set
removeAttributes
(AttributeSet
the old attribute set
old
,
AttributeSet
the attributes
attrs
)

Overrides javax.swing.text.StyleContext.removeAttributes.

Implements javax.swing.text.AbstractDocument.AttributeContext.removeAttributes.

Removes a set of attributes.

private AttributeSet
removeHTMLTags(AttributeSet old, AttributeSet attr)

For any StyleConstants key in attr that has an associated HTML.Tag, it is removed from old.

public void
removeStyle(String
the name of the style to remove
nm
)

Overrides javax.swing.text.StyleContext.removeStyle.

Removes a named style previously added to the document.

public void
removeStyleSheet(StyleSheet
a StyleSheet
ss
)

Removes the StyleSheet ss from those of the receiver.

public void
setBase(URL
a base.
base
)

Sets the base.

public void
setBaseFontSize(int
a font size.
sz
)

Sets the base font size, with valid values between 1 and 7.

public void
setBaseFontSize(String
a font size.
size
)

Sets the base font size from the passed in String.

public Color

Returns:

the color
stringToColor
(String
color string such as "RED" or "#NNNNNN"
string
)

Converts a color string such as "RED" or "#NNNNNN" to a Color.

public AttributeSet

Returns:

the set of CSS attributes.
translateHTMLToCSS
(AttributeSet
AttributeSet containing the HTML attributes.
htmlAttrSet
)

Converts a set of HTML attributes to an equivalent set of CSS attributes.

private synchronized void
unlinkStyleSheet(StyleSheet ss, int index)

Removes references to the rules in ss.

Inherited from javax.swing.text.StyleContext:
addChangeListeneraddStylegetChangeListenersgetCompressionThresholdgetDefaultStyleContextgetEmptySetgetFontgetFontMetricsgetStaticAttributegetStaticAttributeKeygetStylegetStyleNamesreadAttributesreadAttributeSetreclaimregisterStaticAttributeKeyremoveChangeListenertoStringwriteAttributeswriteAttributeSet