Java Class

Not long ago I had an assignment in which I needed to keep track of the times a button was clicked, said article was this: Moving Circle On Click Event using JavaFX? . Now this a new task pretty similar to the one I just mentioned but with the difference of using the scene instead of a button.

You have this assignment:

//********************************************************************
// Write a JavaFX application that counts the number of times the mouse button has been clicked on the scene.
// Display that number at the top of the window.
//********************************************************************

Here it is the solution:

//********************************************************************
// Write a JavaFX application that counts the number of times the mouse button has been clicked on the scene.
// Display that number at the top of the window.
//********************************************************************

/**
 *
 * @author Kevin Uriel Fonseca
 */
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.FlowPane;
import javafx.scene.text.Text;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
import javafx.scene.Group;

public class Class710 extends Application {
    
    // Declare Variables
    private int count = 0;
    private Button button;
    private Text countText;
    private FlowPane panel;
    private static final double MAX_X = 600;
    private static final double MAX_Y = 300;
    
    /*
    *
    * Write function here
    *
    */
    @Override
    public void start(Stage primaryStage){

        // Initiate Variables
        count = 0;
        countText = new Text("Pushes: 0");
        
        panel = new FlowPane(countText);
        
        Group baseDemo = new Group( panel);

        Scene scene = new Scene(baseDemo, MAX_X, MAX_Y);
        scene.setFill(Color.WHITE);
        
        scene.setOnMouseClicked((event)->{
            count++;
            countText.setText("Pushes: " + count);
        });

        primaryStage.setTitle("Draw a Circle when Button is Pressed");
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.show();
        
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        launch(args);
    }
    
}

This is actually what you end up with:

That is it. If you found this article useful, please share it with your friends!.

Leave a Reply

Back to Top