Java FX – GUIs
TOPIC 06 – MOUSE EVENTS

 

 

LESSON NOTE

 

 

IMPLEMENTING EVENTHANDLER<MOUSEEVENT>

 

To make our class able to deal with MouseEvents, we need to add

 

     implements EventHandler<MouseEvent>

 

to the line

 

            public class ClassName extends Application

 

Once we do this, we are committing to including the handle method in our program.  The easiest way to do this is to right click on the class name and choose "Add unimplemented methods".

 

TYPES OF MOUSE EVENTS

 

Here are the types:

  • Mouse clicked (both left and right are the same event)
  • Mouse moved
  • Mouse entered
  • Mouse exited
  • Mouse dragged
  • Mouse pressed
  • Mouse released


LISTENING FOR EVENTS

We can specify which of the above event we want to watch for.  We do this by using:

 

            sceneName.setOnMouseClicked(this);

The line above makes java automatically call the handle method whenever the mouse is clicked anywhere in the scene. 


Of course, if we were interested in watching for mouse movement, then we would use:

 

            sceneName.setOnMouseMoved(this);

 

EVENT DETAILS

 

Inside the handle method, we can access the x and y location of the mouse at the time of the event.  We can also access the event type.  See in the example below how that was done.

 

 

EXAMPLE 1

The following code will allow you to explore the different mouse events and when they are triggered.  The application consists of a simple empty window.  The application outputs messages to console in regards to mouse events that occur.

 

 

Here is the code:

 

import javafx.application.Application;

import javafx.event.EventHandler;

import javafx.scene.Group;

import javafx.scene.Scene;

import javafx.scene.canvas.Canvas;

import javafx.scene.canvas.GraphicsContext;

import javafx.scene.input.MouseEvent;

import javafx.scene.paint.Color;

import javafx.scene.shape.ArcType;

import javafx.stage.Stage;

 

public class BasicMouseEvents extends Application implements EventHandler<MouseEvent>

{

    public void start(Stage primaryStage)

    {

        primaryStage.setTitle("Mouse Events (see console)");

        Group root = new Group();

        Canvas canvas = new Canvas(400, 250);

        GraphicsContext gc = canvas.getGraphicsContext2D();

        root.getChildren().add(canvas);

       

        Scene scene = new Scene(root);

        scene.setOnMouseClicked(this);

        scene.setOnMouseDragged(this);

        scene.setOnMouseEntered(this);

        scene.setOnMouseExited(this);

        scene.setOnMouseMoved(this);

        scene.setOnMousePressed(this);

        scene.setOnMouseReleased(this);

        primaryStage.setScene(scene);

        primaryStage.show();

    }

 

     public void handle(MouseEvent e)

     {

          String coords = "(" + e.getX() + ", " + e.getY() + ")";

          System.out.println("Mouse event >" + e.getEventType() + " " + coords);

     }

    

    public static void main(String[] args)

    {

        launch(args);

    }

}

 

EXAMPLE 2

 

The following example will simply draw a dot at every location that is clicked.  No other mouse events are monitored.



Here is the code:

 

import java.util.ArrayList;

 

import javafx.application.Application;

import javafx.event.EventHandler;

import javafx.scene.Group;

import javafx.scene.Scene;

import javafx.scene.canvas.Canvas;

import javafx.scene.canvas.GraphicsContext;

import javafx.scene.input.MouseEvent;

import javafx.scene.paint.Color;

import javafx.scene.shape.ArcType;

import javafx.stage.Stage;

 

public class Dotting extends Application implements EventHandler<MouseEvent>

{

     public ArrayList<Integer> al;

     public GraphicsContext gc;

 

     public Dotting()

     {

       al = new ArrayList<Integer>();

     }

    

    public void start(Stage primaryStage)

    {

        primaryStage.setTitle("Click to Dot");

        Group root = new Group();

        Canvas canvas = new Canvas(300, 250);

        gc = canvas.getGraphicsContext2D();

        gc.setLineWidth(5);

       

        root.getChildren().add(canvas);

        Scene scene = new Scene(root);

        scene.setOnMouseClicked(this);

       

        primaryStage.setScene(scene);

        primaryStage.show();

       

    }

 

 

     public void handle(MouseEvent e)

     {

          int x = (int) e.getX();

          int y = (int) e.getY();

          al.add(x);

          al.add(y);

          gc.strokeOval(x,y,5,5);

     }

    

    public static void main(String[] args)

    {

        launch(args);

    }

}

 

EXAMPLE 3

 

Here is another example that allows you to click on squares and they change colours.  The squares are stored inside a grid that is simply redrawn every time a click occurs.

 

 

Here is the code:

 

import javafx.application.Application;

import javafx.event.EventHandler;

import javafx.scene.Group;

import javafx.scene.Scene;

import javafx.scene.canvas.Canvas;

import javafx.scene.canvas.GraphicsContext;

import javafx.scene.input.MouseEvent;

import javafx.scene.paint.Color;

import javafx.scene.shape.ArcType;

import javafx.stage.Stage;

 

public class GridClick extends Application implements EventHandler<MouseEvent>

{

     public int[][] grid;

     public int rows;

     public int cols;

     public GraphicsContext gc;

 

     public GridClick()

     {

          rows = 10;

          cols = 15;

         grid = new int[rows][cols];

         for(int r=0; r<rows; r++)

         {

               for (int c=0; c<cols; c++)

               {

                   grid[r][c] = 0;

               }

         }

    }

    

    public void start(Stage primaryStage)

    {

        primaryStage.setTitle("Click on Grid");

        Group root = new Group();

        Canvas canvas = new Canvas(400, 400);

        gc = canvas.getGraphicsContext2D();

        gc.setLineWidth(5);

       

        root.getChildren().add(canvas);

        Scene scene = new Scene(root);

       

        scene.setOnMouseClicked(this);

       

        primaryStage.setScene(scene);

        primaryStage.show();

        drawGrid();

       

    }

 

    public void drawGrid()

    {

         for(int r=0; r<rows; r++)

         {

               for (int c=0; c<cols; c++)

               {

                   if (grid[r][c] == 0)

                   {

                        gc.setFill(Color.BLUE);

                   }

                   else if (grid[r][c] == 1)

                   {

                        gc.setFill(Color.RED);

                   }

                   gc.fillRect(40*r, 40*c, 40, 40);

               }

         }  

    }

   

    public int rowFromX(int x)

    {

         return (int)(x/40.0);

    }

    public int colFromY(int y)

    {

         return (int)(y/40.0);

    }

 

     public void handle(MouseEvent e)

     {

          int x = (int) e.getX();

          int y = (int) e.getY();

          int r = rowFromX(x);

          int c = colFromY(y);

          grid[r][c]=1;

          drawGrid();

     }

    

    public static void main(String[] args)

    {

        launch(args);

    }

}