Example app
Practice tracker
Reuse a score display with your own counting rules.
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/practice/Main.java →
src/main/java/Main.java - examples/shared/ScoreDisplay.java →
src/main/java/ScoreDisplay.java
Run App to rebuild. These examples run in VS Code, in a separate JavaFX window.
Open related lessonRead the source
practice/Main.java
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import zero.SimpleApp;
/** A second app reuses the exact same ScoreDisplay class. */
public class Main extends SimpleApp {
private int completed;
private ScoreDisplay score;
@Override public void settings() {
title("Practice tracker");
size(420, 240);
}
@Override public void setup() {
score = new ScoreDisplay("Completed");
Button add = new Button("Completed an exercise");
Button reset = new Button("Reset");
add.setOnAction(event -> completeExercise());
reset.setOnAction(event -> resetProgress());
VBox screen = new VBox(12, score.view(), add, reset);
screen.setPadding(new Insets(20));
show(screen);
}
private void completeExercise() {
completed++;
score.setScore(completed);
}
private void resetProgress() {
completed = 0;
score.setScore(completed);
}
public static void main(String[] args) { launch(args); }
}
shared/ScoreDisplay.java
import javafx.scene.Node;
import javafx.scene.control.Label;
/** An ordinary class: the app owns the number; this object displays it. */
public class ScoreDisplay {
private final Label label;
private final String caption;
public ScoreDisplay() {
this("Score");
}
public ScoreDisplay(String caption) {
this.caption = caption;
label = new Label(caption + ": 0");
}
public void setScore(int points) {
label.setText(caption + ": " + points);
}
public Node view() {
return label;
}
}