Eric Bruno is a contributing editor to Dr. Dobb's and co-author of JavaFX: Developing Rich Internet Applications.
JavaFX contains a bevy of controls to do all sorts of things: a list view to scroll through and select from; a drop-down list view; button; text box; label; progress bar; slider; the list goes on. However, the list view control lacks one feature I've found a need for many times: multi-select. I simply want to be able to select more than one item in the list, and then get back an array of the items selected when I query for them. But alas, the stock JavaFX list view control won't do it. How did I work around this problem? Like any good developer, I rolled my own.
While I don't advocate reinventing the wheel at the drop of a hat, I've a real need for this feature, and JavaFX does support the notion of creating custom controls. In fact, I found that it's quite easy to do. With little effort, and relatively little code, I was able to build exactly what I needed. Before we get into the details of my multi-select list view control, let's examine custom controls in general.
Custom Controls
You have two choices to build a custom control in JavaFX. First, you can write a class that extends javafx.scene.CustomNode. Since all UI components in JavaFX are Node objects, this approach is reasonable. To begin, extend CustomNode, override the children variable with your own Node content, and then implement your new Node's behavior. Voila! custom control.
The second choice is to extend the javafx.scene.control.Control class. This seems to make more sense to me, since what you have as a result is a class that "is a" Control in terms of the object relationship. That happens to be exactly what you intend to do: build a custom control. As a result, the choice I made was to extend the Control class. This has some benefits:
- Since you need to define a CustomSkin class, your control is skin-able
- Your control is more easily managed by the JavaFX layout manager
The only requirement, as mentioned above, is to define two classes: one that extends Control, and another that extends javafx.scene.control.Skin. Your custom Skin class will mainly define how the control looks, while your Control class will mainly define its behavior. In a custom control, both of these classes will know about each other through member variables, as in Figure 1.

Now that we've discussed custom controls in general, let's take a look at how to build the multi-select list view control in detail. For a helpful code template to get you started building your own controls, you can use the code for this project as a start, or see the JavaFX Control Template (Johannes Schneider).