Saturday, June 14, 2008

Java CSS

Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g. fonts, colors, spacing) to Web documents. Java CSS is Java implementation of CSS which differs in some aspects, but overall concept is same.

Example


Java CSS documents look much like their HTML CSS.

Component {
font-family: "SansSerif";
font-size: 14;
font-weight: normal;
}

JLabel#title {
font-size: 24;
font-weight: bold;
foreground: #0099ff;
border: etchedBorder;
}

JButton:mouseover {
font-weight: bold;
}

JButton.toolbar {
text: null;
}

The :mouseover in JButton:mouseover is known as a pseudoclass, and it means "only when the mouse is over the component". So JButtons will normally have font-weight: normal (because of the Component rule), but will switch to bold text when the mouse is over them. JButtons with the "toolbar" style class (according to getClientProperty("styleClass")) will additionally have their text set to null.

Using Stylesheets

You can create a stylesheet using one of its constructors and then apply it to the appropriate components using applyTo():

FileReader in = new FileReader("example.css");
Stylesheet stylesheet = new Stylesheet(in);
in.close();
stylesheet.applyTo(mainFrame);

You can also set a stylesheet as the global stylesheet with Stylesheet.setGlobalStylesheet(). The global stylesheet is automatically applied to all windows as they are displayed.

Differences from HTML

Many readers will be familiar with CSS as it applies to HTML documents. The Java CSS implementation has some important differences relative to HTML CSS:

* Java property names are used throughout. A label's color, for example, is controlled with "foreground" after its Java property name instead of the HTML CSS property "color".
* The set of available properties is different. JPanel, for example, has no equivalent to HTML's "background-image" property. On the other hand HTML has no equivalent to the JSlider property "majorTickSpacing" -- in fact it doesn't even offer sliders to begin with!
* Not all CSS selectors are supported. For example, there is currently no way to specify "all JLabels which are children of a JPanel".
* Java CSS's pseudoclasses are more powerful and useful. HTML has no equivalent to Java's programmatic pseudoclasses.

There are many other minor differences, but these are by far the most significant.

Reference:

https://javacss.dev.java.net/docs/overview.html

0 Java Junction comments: