Wiki / Gameplay Workshop
Make a Canvas button update a counter
Create a keypad-usable button, report clicks on screen, and extend its event with Java Behaviour code.
Lay out the Canvas controls
Open a new project and switch to Canvas. Use + UI → Text to add a status label, then + UI → Button to add a button. On a fresh Canvas these widgets receive IDs text and button. Select each widget in the Hierarchy and use Rect Transform → Offset or drag it in the Canvas view so the label sits above the button. Set the Text widget's displayed text to Ready and the Button's text to Tap.
With the button selected, set On Click in the Inspector's Events section to tapped. Studio stores the click as a named Canvas event. If you want a quick no-code response instead, set the button's Default action to Set label text, choose the status label in Label, and enter a message in New text.
Add the live counter behaviour
Select the starter cube and choose Add Component… → Java Behaviour. Name the class ButtonCounter. Studio registers the source and attaches it to the cube. Replace its source with the example below. The widget IDs match the fresh Canvas sequence above; if your IDs differ, copy them from the ui.root.children entries in assets/Main.scene.json and change the two strings in the code.
The runtime calls onCanvasEvent with the widget ID, trigger (click), and the event name you entered. setUiText changes the authored Text widget while the MIDlet is running. Java Behaviours run in Test MIDlet; desktop Play previews Canvas layout but does not run this Java callback.
package game;
import dev.j2me.runtime.SceneBehaviour;
public final class ButtonCounter extends SceneBehaviour {
private int taps;
protected void onCanvasEvent(String widgetId, String kind, String event) {
if (!"button".equals(widgetId) || !"click".equals(kind) ||
!"tapped".equals(event)) return;
taps++;
setUiText("text", "Pressed " + taps);
}
}Try it on the keypad
Save the scene and click Test MIDlet. Canvas focuses its first interactable button; if you have added other controls, use a direction key to focus Tap. Press Numpad 5 (the center/select action). Each press changes the label to Pressed 1, Pressed 2, and so on. On a real phone use its center/select key; the physical key code can differ by handset.