Resizable Grid Using Canvas

Inspired by Jasper Potts post showing how to create a resizable “DotGrid” in JavaFX using the Canvas API I went ahead and modified a bit, because I needed a similar approach for a contribution.

So I changed the visuals to actually draw a grid (horizontal and vertical lines) instead of dots and added styleable CSS properties to customize grid size and color via CSS.

You can view the final Code at Github. If you are concerned about its performance, you may even increase its speed by only redrawing the part of the canvas that has changed..

Using JavaFX's Properties

First a general reminder: Do not get into micro-optimization - It clutters the code for little to no benefit!

So with JavaFX we got a very nice API for writing user interface applications and with Java 8’s Lambda Expressions it is even more fun. Just a single line of code is needed to wire up a new listener:

1
event.resultStatusProperty().addListener(obs -> doMagic());

JavaFX Color Derivation

A very powerful and often underestimated feature of JavaFX is its CSS Color Derivation.
But let us start at the beginning by explaining two prerequisites:

  1. The Default JavaFX 8 Theme (Modena) only defines a few colors statically in its stylesheet. The rest is derived by JavaFX’s color functions (ladder and derive - see the CSS Reference) or referenced as color variables.
  2. If you start to apply a custom styles to a Node in the scenegraph, these styles will also be applied to all children of this Node (if applicable). So changing a color variable on a single node will change the corresponding colors, derived colors and referenced colors on all child nodes in the scenegraph, but not on any of its parent nodes.

If we combine both together we can create these three Buttons with ease (the first one is a regular one, just to show the default theme):
Java FX Color derivation example

Hello World

I just finished developing my first Octopress theme.

I hope to add some meaningful content soon ;-)