Time for action – using custom CSS classes

Very often when building a user interface, there will be a need to repeat styles across different components in the application. Instead of using the generic class type, or having to encode multiple styles on a part-by-part basis, CSS classes can be used to define a standard style and applied to individual widgets.

A label will be added to the sample part and associated with a CSS style, and that will be stored in the default CSS file.

  1. Open the Hello class and go to the create method that creates the part's UI.
  2. At the end of the method, add a new Label, which will be used to demonstrate the styling:
    Label label = new Label(parent, SWT.NONE);
    label.setText("Danger Will Robinson!");
  3. Associate the label with a custom CSS class using the setData method on the SWT widget along with the org.eclipse.e4.ui.css.id key and the name of the CSS class:
    label.setData("org.eclipse.e4.ui.css.id", "DireWarningMessage");
  4. Finally add the class to the default.css file so that it can be rendered appropriately:
    #DireWarningMessage {
      color: red;
      background-color: yellow;
    }
  5. Run the application and the warning message should be shown at the bottom of the part in the style chosen:
    Time for action – using custom CSS classes

What just happened?

Any SWT widget can have an arbitrary amount of data stored with it using the setData method, which can be queried by any other code using the corresponding getData method. This is used by the rendering engine that configures how widgets should be rendered in the user interface.

The org.eclipse.e4.ui.css.id key is used to identify the CSS class name that should be used when styling the widget through the Eclipse 4 platform, and by using a common key, the application can have the same and consistent style applied to a number of different components.

Tip

This key is defined in the CSSSWTConstants class in the org.eclipse.e4.ui.css.swt bundle if a compile time reference is desired.

Note that unlike HTML elements, a widget can only have a single CSS class, so it is not possible to have multiple classes associated with an element.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.128.248