Skip to content

Custom Widgets

Widgets are essentially containerized rendering components that can be added to a screen, and can be interacted with by the player through various events such as mouse clicks, key presses, and more.

Creating A Widget

There are multiple ways to create a widget class, such as extending ClickableWidget. This class provides a lot of useful utilities, such as managing width, height, position, and handling events - it implements the Drawable, Element, Narratable, and Selectable interfaces:

  • Drawable - for rendering - Required to register the widget to the screen via the addDrawableChild method.
  • Element - for events - Required if you want to handle events such as mouse clicks, key presses, and more.
  • Narratable - for accessibility - Required to make your widget accessible to screen readers and other accessibility tools.
  • Selectable - for selection - Required if you want to make your widget selectable using the Tab key - this also aids in accessibility.
java
public class CustomWidget extends ClickableWidget {
	public CustomWidget(int x, int y, int width, int height) {
		super(x, y, width, height, Text.empty());
	}

	@Override
	protected void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) {
		// We'll just draw a simple rectangle for now.
		// x1, y1, x2, y2, startColor, endColor
		int startColor = 0xFF00FF00; // Green
		int endColor = 0xFF0000FF; // Blue

		context.fillGradient(getX(), getY(), getX() + this.width, getY() + this.height, startColor, endColor);
	}

	@Override
	protected void appendClickableNarrations(NarrationMessageBuilder builder) {
		// For brevity, we'll just skip this for now - if you want to add narration to your widget, you can do so here.
		return;
	}
}

Adding The Widget To The Screen

Like all widgets, you need to add it to the screen using the addDrawableChild method, which is provided by the Screen class. Make sure you do this in the init method.

java
// Add a custom widget to the screen.
// x, y, width, height
CustomWidget customWidget = new CustomWidget(40, 80, 120, 20);
this.addDrawableChild(customWidget);

Custom widget on screen.

Widget Events

You can handle events such as mouse clicks, key presses, by overriding the onMouseClicked, onMouseReleased, onKeyPressed, and other methods.

For example, you can make the widget change color when it's hovered over by using the isHovered() method provided by the ClickableWidget class:

java
// This is in the "renderWidget" method, so we can check if the mouse is hovering over the widget.
if (isHovered()) {
	startColor = 0xFFFF0000; // Red
	endColor = 0xFF00FFFF; // Cyan
}

Hover Event Example