Custom nodes
When no built-in node draws what you need or behaves the way you need, write your own.
A custom node is a class that extends Node: it draws itself, takes its properties through fluent setters, reacts to the mouse and fires events, like the nodes JOID ships.
You will learn
- How to write a node that draws itself
- Which hooks of a node you can override, and how a node places its children
- How to give a node a property that follows a signal
- How a node reacts to the mouse and holds a value that the user changes
- How to fire an event of your own, and make the node duplicable
Write a node that draws itself
Section titled “Write a node that draws itself”A node needs a constructor, a factory and a draw method.
This one draws a dot inside its bounds:
public class DotNode extends Node {
private static final Color ELEMENT = new Color(38, 43, 53).lock(); private static final Color ACCENT = new Color(91, 140, 255).lock();
protected DotNode(final double x, final double y, final double width, final double height) { super(x, y, width, height); }
public static DotNode create(final double x, final double y, final double size) { return new DotNode(x, y, size, size); }
@Override public void draw(final double mouseX, final double mouseY) { final double centerX = super.getX() + super.dw(2D); final double centerY = super.getY() + super.dh(2D); DrawUtils.SHAPE.drawCircle(centerX, centerY, DotNode.ELEMENT, super.dw(2D)); DrawUtils.SHAPE.drawCircle(centerX, centerY, DotNode.ACCENT, super.dw(4D)); }
}It attaches, nests and positions like any built-in node:
ContainerNode.create(100, 130, 400, 140).body(container -> { DotNode.create(20, 20, 100).attach(container); DotNode.create(150, 20, 100).attach(container); DotNode.create(280, 20, 100).attach(container);}).attach(this);
The constructor is protected, so that the class can be extended, and takes the position and the size in design pixels.
The public static factory create(...) returns the concrete type, so that a chain of setters can follow it.
draw(mouseX, mouseY) runs on every frame while the node is visible.
It draws in the coordinates of the parent: the node sits at getX(), getY(), and its size is getWidth() × getHeight().
mouseX and mouseY are in design pixels of the UI; Node.toDrawX and toDrawY(y) convert such a position into the coordinates where draw draws.
dw(2D) is the width divided by 2; Position and size lists these helpers.
Drawing shapes and text teaches the DrawUtils calls.
Override the hooks you need
Section titled “Override the hooks you need”Node implements INode, whose hooks JOID calls at each step of the life of a node.
Every hook does nothing by default, except drawSkeleton; override only the ones your node needs:
| Hook | JOID calls it |
|---|---|
init(UI ui) | Each time the node joins a UI, after its children. A node can join several times: keep it repeatable. |
update() | Once per frame, in the update step, after its children; a hidden node runs it too. |
layout() | On every frame while the node is visible, right before it draws: place the children here, with layoutPosition on each child (Place the children yourself). |
draw(double mouseX, double mouseY) | On every frame while the node is visible and its wait conditions hold. |
drawSkeleton(double mouseX, double mouseY) | Instead of draw while a wait condition fails. It fills the bounds with Color.LOADING by default. |
mousePressed, mouseReleased, mouseDragged, mouseScroll | For every mouse event that reaches the node. |
keyPressed, keyReleased, charTyped | For every key and every typed character that reach the node. |
detach() | When the node leaves its UI, after its children. Release here what init or draw acquired. |
Draw once, reuse every frame shows a node that deletes its framebuffer in detach().
An exception thrown by update or detach is printed once as a warning, and the next frames go on.
Node lifecycle places each step in the life of a node, and The frame lifecycle places draw among the children, the effects and the layers.
A hook is the node’s own step; the listeners that users add with onX(...) and handleX(...) run around it.
None of these hooks is final, so a subclass of a built-in node overrides them too.
Place the children yourself
Section titled “Place the children yourself”A node that places its children by a rule of its own overrides layout().
This one splits its width between its children, with a gap of 10 design pixels:
@Overridepublic void layout() { final List<Node> panels = new ArrayList<>(); for (final Node child : super.getChildren()) { if (child.isVisibleProperty() && child.getPosition() != PositionProperty.ABSOLUTE) { panels.add(child); } }
final double width = (super.getWidth() - 10D * (panels.size() - 1)) / panels.size(); for (int i = 0; i < panels.size(); i++) { panels.get(i).layoutPosition((width + 10D) * i, 0D).fit(width, super.getHeight()); }}SplitNode.create(120, 400, 520, 120).body(split -> { RectNode.create(0, 0, 0, 0).color(CustomNodesUI.MUTED).attach(split); RectNode.create(0, 20, 0, 80).color(CustomNodesUI.MUTED).attach(split); RectNode.create(0, 0, 0, 0).color(CustomNodesUI.MUTED).attach(split);}).attach(this);
y of 20 and its height of 80 inside it.
Node.layoutPositiongives a child its slot; thexandyof the child stay an offset inside it, so that the user of your node can still move it.Node.fitgives the size of the slot to a child created with a length of 0, and keeps a length that the child declares.Node.layoutSizeimposes a size on the frame, whatever the child declares, without changing its declared size.- Skip the children whose own
visibleisfalse, read withNode.isVisibleProperty, and theABSOLUTEones, as the layouts of JOID do. Do not testisVisible(): it is alsofalsefor a child scrolled out of view, so a layout that skips on it moves the other children while the user scrolls.
A layout that changes the order of its children, as a reorderable list does, gives the new order to Node.reorderChildren, which the drawing follows too.
Give the node a property
Section titled “Give the node a property”The swatch of the next sections is a square of color that the user selects with a click.
Its color is a property: a value setter and a Supplier setter, like every property of the built-in nodes.
public final <T extends SwatchNode> T color(final Color color) { return this.color(Signal.from(color));}
public final <T extends SwatchNode> T color(final Supplier<Color> color) { return super.follow("color", color, value -> this.color = value);}Node.follow applies the value at once and keeps the source: before the node draws, JOID asks the source again and calls the consumer when the value differs.
A Supplier that reads signals is computed again only when one of them changes; Signals explains when JOID computes a value again.
The value setter passes its argument to Signal.from, which gives a constant that follow applies once and does not keep.
The first argument names the property: a second call with the same name replaces the first source.
Node.start applies a plain value once and drops the source of the property, and Node.bind binds the property to a writable signal both ways, Node.bindNullable when the signal can hold null.
When the node changes such a property itself, Node.sync writes the new value back to the bound signal; a value that the user changes belongs in an InteractiveValue instead (Hold a value that the user changes).
A setter is public final, generic in <T extends YourNode>, returns (T) this through the helper, and is named after the property, without set.
The node draws with the field:
@Overridepublic void draw(final double mouseX, final double mouseY) { DrawUtils.SHAPE.drawRect(super.getX(), super.getY(), super.w(), super.h(), this.color); if (this.selected) { DrawUtils.SHAPE.drawBorder(super.getX(), super.getY(), super.w(), super.h(), SwatchNode.TEXT, 8D); }}When a property is required, refuse the node at once with Node.require in the constructor: the node throws IllegalStateException with your advice when it joins a UI without it.
React to the mouse
Section titled “React to the mouse”The swatch overrides mousePressed to toggle its selection:
@Overridepublic void mousePressed(final NodeMouseEvent<?> event) { if (event.isConsumed() || !event.getButton().isLeft() || !super.isHovered()) { return; }
this.selectedValue.set(!this.selectedValue.get()); event.consume();}The hook receives every press that reaches the node, wherever the pointer is.
isHovered() tells whether the pointer is on the node, event.isConsumed() whether a node in front already took the press, and event.consume() stops it for the nodes behind and the UIs below.
The children in front of the node and its own handleMousePressed listeners hear the press first; Events explains this path and consumption.
The other input hooks follow the same pattern.
A node scrolled out of the area of its container receives no input, unless Node.holdsInput returns true: override it to keep the input while a gesture of the node goes on, as a focused text field does.
Hold a value that the user changes
Section titled “Hold a value that the user changes”selected changes on a click, from a setter and from a signal, and the users of the swatch want to hear each change, or refuse it.
An InteractiveValue holds such a value, like the value of every built-in control:
public class SwatchNode extends Node {
private static final Color TEXT = new Color(231, 233, 238).lock();
private static final EventType<NodeChangeEvent.Pre<?, Boolean>> BEFORE_SELECT = EventType.create("beforeSelect"); private static final EventType<NodeChangeEvent.Post<?, Boolean>> SELECT = EventType.create("onSelect"); private static final EventType<NodeEvent<SwatchNode>> RESET = EventType.create("onReset");
private final transient InteractiveValue<Boolean> selectedValue;
private Color color; private boolean selected;
protected SwatchNode(final double x, final double y, final double width, final double height) { super(x, y, width, height);
this.color = SwatchNode.TEXT; this.selectedValue = InteractiveValue .create(super.getBindings(), "selected", () -> this.selected, value -> this.selected = value) .events( SwatchNode.BEFORE_SELECT, (previous, next) -> NodeChangeEvent.Pre.create(this, previous, next), SwatchNode.SELECT, (previous, next) -> NodeChangeEvent.Post.create(this, previous, next) ); }
public static SwatchNode create(final double x, final double y, final double size) { return new SwatchNode(x, y, size, size); }InteractiveValue.create takes the bindings of the node (getBindings()), the name of the property, a getter and a setter of the field.
events(...) names the two events of a change: a beforeX event that a listener can cancel, then an onX event that tells what happened.
The fluent methods of the node hand each call to the value:
public final <T extends SwatchNode> T selected(final boolean selected) { return this.selectedValue.start(selected);}
public final <T extends SwatchNode> T selected(final Signal<Boolean> selected) { return this.selectedValue.bind(selected);}
public final <T extends SwatchNode> T change(final boolean selected) { this.selectedValue.change(selected); return (T) this;}
public final <T extends SwatchNode> T beforeSelect(final EventListener<NodeChangeEvent.Pre<T, Boolean>> listener) { return this.selectedValue.before(listener);}
public final <T extends SwatchNode> T onSelect(final EventListener<NodeChangeEvent.Post<T, Boolean>> listener) { return this.selectedValue.on(listener);}start(value)gives a start value.bind(signal)follows a writable signal and writes the changes of the user back to it; a signal that cannot be written throwsIllegalArgumentException.change(value)changes the value as the user would:beforeSelectcan refuse it, thenonSelectfires.- In an input hook,
set(value)applies the value when the hook ends, andget()already reads it. clamp(operator)brings every requested value into the bounds of the node, andreapply()asks for the pending value again after the bounds change.
The UI owns the signal and reads it anywhere:
final BooleanSignal favorite = new BooleanSignal(false);final IntegerSignal changes = new IntegerSignal(0);ContainerNode.create(600, 130, 560, 140).body(container -> { SwatchNode .create(20, 20, 100) .color(CustomNodesUI.ACCENT) .selected(favorite) .onSelect(event -> changes.increment()) .attach(container); TextNode .create(160, 30) .text(Text.create(favorite.get() ? "Favorite" : "Plain", info)) .attach(container); TextNode.create(160, 70).text(Text.create("Changes: " + changes.get(), info)).attach(container);}).attach(this);onSelect.
The events fire on every real change, whatever its source, and never when the value stays the same. Controls explains the order of these events and the pending value.
Fire an event of your own
Section titled “Fire an event of your own”An event that is not the change of a value, such as a reset, needs an EventType, a listener method and a call to Node.fire:
public final <T extends SwatchNode> T reset() { this.selectedValue.change(false); super.fire(SwatchNode.RESET, () -> NodeEvent.create(this)); return (T) this;}
public final <T extends SwatchNode> T onReset(final EventListener<NodeEvent<T>> listener) { return super.listen(SwatchNode.RESET, listener);}EventType.create(name) creates the type once, in a static field.
Node.listen adds a listener of that type, and fire(type, supplier) builds the event and calls the listeners.
The event is a NodeEvent that carries the node.
For an event that carries a change, use NodeChangeEvent, whose Pre form a listener can cancel.
Make your node duplicable
Section titled “Make your node duplicable”copy() and the ghost of a drag of type COPY build your node again with its (x, y, width, height), (x, y) or argument-free constructor, the first one it finds, then copy its fields.
A node with none of them overrides Node.instantiate to build itself.
The swatch keeps the value that the user changes in a field that belongs to its own instance:
private final transient InteractiveValue<Boolean> selectedValue;Mark transient a field that belongs to one instance only, such as this one, a framebuffer or a cache: the copy leaves it out, and keeps what its own constructor gives it.
A field that the copy cannot set throws IllegalStateException with the name of the field.
Position and size explains what copy() gives.
- A custom node extends
Node, with aprotectedconstructor(x, y, width, height)and acreate(...)factory. drawruns on every frame, in the coordinates of the parent: the node sits atgetX(),getY().- Override only the hooks you need:
init,update,layout,draw, the input hooks anddetach. - A layout node places each child with
layoutPositionand sizes it withfit. - Each property has a value setter and a
Suppliersetter, both throughfollow. - An input hook checks
isHovered()andisConsumed(), then callsconsume(). - A value that the user changes lives in an
InteractiveValue, withstart,bind,changeand abeforeX/onXpair. - An event of your own is an
EventType, alistenmethod and afirecall. - A field of one instance only is
transient, so thatcopy()leaves it out.
Try it
Section titled “Try it”React to the right button. Make the swatch toggle on a right click only.
Solution
In mousePressed, test the other button:
if (event.isConsumed() || !event.getButton().isRight() || !super.isHovered()) {Refuse a selection.
In the UI, keep the swatch from being selected while a BooleanSignal locked holds true.
Solution
Cancel the beforeSelect event:
.beforeSelect(event -> { if (locked.peek()) { event.cancel(); }})Count the resets.
Add a button that calls reset() on the swatch, and show how many times onReset fired.
Solution
Keep the swatch in a local variable, call swatch.reset() from the onClick of a RectNode, and count in onReset:
swatch.onReset(event -> resets.increment());