Thompson Rivers University
Question 2
Lab 5 JavaFX - SM 2025In the PushCounter program, why was the count primitive variable and the Text object declared at the class level? Why wasn’t anything else, such as the Button?
PushCounter.java
public class PushCounter extends Application {
private int count;
private Text countText;
@Override
public void start(Stage primaryStage) {
count = 0; // start the counter at 0
countText = new Text("Pushes: 0"); // display starting text
// Create a button
Button push = new Button("Push Me!");
// Set the action that happens when the button is pressed
push.setOnAction(this::processButtonPress);
// Layout the components using a FlowPane
FlowPane pane = new FlowPane(push, countText);
pane.setAlignment(Pos.CENTER);
pane.setHgap(20); // horizontal spacing between button and text
pane.setStyle("-fx-background-color: cyan");
// Set up the scene and stage
Scene scene = new Scene(pane, 300, 100);
primaryStage.setTitle("Push Counter");
primaryStage.setScene(scene);
primaryStage.show();
}
// This method runs when the button is pressed
public void processButtonPress(ActionEvent event) {
count++; // increment the counter
countText.setText("Pushes: " + count); // update the text
}
public static void main(String[] args) {
launch(args);
}
}Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 54 more lessons in Thompson Rivers University.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.