Styles

This chapter provides an introduction to two style-related subjects used when creating custom components:

  1. Overriding the component class' applyStyle() method to allow developers to quickly set properties on many components based on a single nextapp.echo.Style object.
  2. Using CSS styles to create effects when rendering rendered components into HTML.

Using Style Descriptors in Components

The nextapp.echo.Style class provides the capability to encapsulate component style properties into a single object and then apply them to many different components. Custom-built components can take advantage of this capability by overriding the applyStyle() method of the Component class and providing custom style property names. If a component overrides applyStyle() its first operation should be to call super.applyStyle(), such that the component from which it is derived will have its style properties applied. Calling super.applyStyle() is even necessary if the component is derived directly from the nextapp.echo.Component class.

Using CSS Styles in Rendered HTML

The preferred method of defining style attributes in HTML documents rendered by Echo is to use CSS styles. In many Echo documents, nearly every HTML element will have a class attribute referencing a CSS style. In order to keep the size of served documents reasonable, the application container will reuse styles as necessary among elements. If each element had its own independent style, Echo documents would be several times larger than necessary, with the vast majority of the document dedicated to CSS style information. To accommodate the reuse of styles, it is necessary to follow a specific procedure for assigning style attributes when rendering the HTML of custom components.

The following source code shows the render() method of an example rendering peer class:

    public void render(RenderingContext rc, Element parent) {
        HtmlDocument doc = rc.getDocument();
        ComponentStyle style = ComponentStyle.forComponent(this);

        style.addElementType("span");
        String styleName = doc.addStyle(style);
        Element spanElement = new Element("span");
        spanElement.addAttribute("class", styleName);
        spanElement.addText("Test");
        parent.addElement(spanElement);
    }
Step Description Code
1 Create a ComponentStyle object for the rendering peer. ComponentStyle style =
  ComponentStyle.forComponent(this);
2 Add any element names that will use the CSS style using addElementType(). style.addElementType("span");
3 Add the style to the document using HtmlDocument.addStyle(), which returns the style name. String styleName = 
  doc.addStyle(style);
4 Add a class attribute to HTML elements that use the style. spanElement.addAttribute("class",
  styleName);