Example app
Mini quiz
Buttons, answer feedback and once-only scoring.
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/quiz/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
quiz/Main.java
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import zero.SimpleApp;
/** Start here: fields, objects, and a method called by a button click. */
public class Main extends SimpleApp {
private int points;
private TextField answer;
private Label feedback;
private Button check;
private ScoreDisplay score;
@Override public void settings() {
title("Mini quiz");
size(420, 300);
}
@Override public void setup() {
Label question = new Label("What is 6 × 7?");
answer = new TextField();
answer.setPromptText("Answer");
check = new Button("Check answer");
feedback = new Label("Enter an answer.");
score = new ScoreDisplay();
check.setOnAction(event -> checkAnswer());
VBox screen = new VBox(12, question, answer, check, feedback, score.view());
screen.setPadding(new Insets(20));
show(screen);
}
private void checkAnswer() {
if (answer.getText().trim().equals("42")) {
points += 10;
score.setScore(points);
feedback.setText("Correct!");
check.setDisable(true); // Award this question only once.
} else {
feedback.setText("Try again.");
}
}
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;
}
}