Example app
Canvas counter
Native buttons and a canvas in the same app.
Run this example
Stop the app and save your current Main and helpers outside src/. Copy the files shown below into the listed destinations in your standalone starter, creating resource folders when needed. Replace Main and the listed helpers. Keep the zero/ framework folder and build files. If an older downloaded kit does not have these examples, use the source shown here.
- examples/counter/Main.java →
src/main/java/Main.java
Run App to rebuild. These examples run in VS Code, in a separate JavaFX window.
Open related lessonRead the source
counter/Main.java
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import zero.SketchApp;
/** Ordinary JavaFX controls can live beside the Zero canvas. */
public class Main extends SketchApp {
private int count;
private Label total;
@Override
public void settings() {
size(480, 240);
title("Click counter");
}
@Override
public void setup() {
total = new Label("Count: 0");
Button add = new Button("Add one");
Button reset = new Button("Reset");
add.setOnAction(event -> {
count++;
total.setText("Count: " + count);
});
reset.setOnAction(event -> {
count = 0;
total.setText("Count: " + count);
});
HBox controls = new HBox(12, add, reset, total);
controls.setPadding(new Insets(12));
layout().setBottom(controls); // The normal JavaFX BorderPane escape hatch.
}
@Override
public void draw() {
background(Color.BEIGE);
fill(Color.DARKSLATEGRAY);
textSize(24);
text("You clicked " + count + " times.", 24, 70);
textSize(16);
text("Buttons change a field; draw reads that field.", 24, 110);
}
public static void main(String[] args) {
launch(args);
}
}