Using Dynamic Styles

You can think of a Style object as a freestanding collection of properties. The term style is borrowed from the word processing world where the editing of a style sheet is independent of the documents to which you apply it. The same is true for using and applying Style objects in this library.

As an example, your boss tells you that the new corporate color is red and you need to change the color of elements in your HTML pages. You can, of course, set properties directly on elements, which is the traditional model for GUI framework programming:

       // old way of doing things...
       DhText t1 = new DhText();
       DhText t2 = new DhText();
       t1.setColor( Color.RED );
       t1.setFont( "arial");
       t2.setColor( Color.RED );
       t2.setFont( "arial");
    

You could, of course, use derivation to save yourself time. For example, you might consider improving this with the following code:

       // old way of doing things a little better...
       public class MyText extends DhText
       {
          public MyText()
          {
              setColor( Color.RED );
              setFont( "arial" );
          }
    

This works fine until you decide you also want those settings for buttons, labels, tabs, documents, and so on. And you’ll find yourself with even more work when you apply these to another part of your program or to another program.

The answer to this problem is a Style object. While using this library, you can instantiate a Style object and set its properties at any point:

       // STEP 1: Create style objects.

       DhStyle myStyle = new DhStyle();

       // STEP 2: Set properties on style objects

       myStyle.setColor( Color.RED );
       myStyle.setFont( "arial" );
    

Then at any other time in the code, you can apply that style to any number of elements:

       DhText t1 = new DhText();
       DhText t2 = new DhText();

       // STEP 3: Apply styles using the setStyle method.

       t1.setStyle( myStyle );
       t2.setStyle( myStyle );
    

When it's time to keep up with the dynamic nature of high-level policy setting at your corporation, the following line sets all instances of all elements with myStyle set on them to change color:

       myStyle.setColor( Color.BLUE );
   

Here is the really powerful part: all this is available during run time. Every time you make a change to the Style object, the DHTML run time dynamically reaches back and updates all elements to which that Style object is applied.

For more information, see Understanding Style Inheritance.