In the previous example I showed how we can add custom graphics to our user interface. However, what if we would like to make these graphics interactive. For example, if we wished to make a graph display, where you could interact with the graph. Well, because a Canvas is-a Component we can add Mouse Events to our custom canvas. Mouse Events are a mechanism for deciding how the mouse should behave when it interacts with our custom canvas - so, what should happen on the custom canvas when you press and release the mouse button.
In this example we would like to draw a red circle around the point that was chosen. In this case the circle will have a radius of 10 pixels.
Figure X. Canvas Applications with Events
So, the application remains largely unchanged as below:
But, we add Mouse Events to the Custom Canvas. You can see here that this class now implements MouseListener and has additional methods to describe what happens when: the mouse is clicked; the mouse enters the canvas region; the mouse exits the canvas region; the mouse button is pressed (but not release); and, the mouse button is released (having subsequently been pressed).
This application uses the interface
MouseListener, by using the keyword
implements. When we use an interface in our code we are required to write code for the methods defined in that interface. In this case we are using the interface
MouseListener which has five methods that must be implemented
mouseClicked(). As you can see in the code segment above, I only really required
mouseClicked() as I only wanted a circle to be added when the mouse was clicked. However, I was required to write code for the four other methods and I did, by writing blank functionality for those methods - so nothing will occur when the other four events occur.
As well as writing the code for the events that occur, we also have to "turn on" Mouse Listening. We do this by using the line of code
this.addMouseListener(this); What we are doing is stating "To this
CustomCanvasMouse object turn on Mouse Listening - and if a mouse event occurs then send it to this
CustomCanvasMouse object". Our custom canvas is now ready to listen for events and pass them to its own five mouse methods.
Finally - one small point. At the top of the code I wrote
import java.awt.*; and I also wrote
import java.awt.event.*;. This may seem unnecessary but it is not. We need the
MouseEvent class from the
java.awt.event package for our code, but does the
import java.awt.*; not also import the classes in the
java.awt.event package? No, it does not! - the * is not recursive and so does not import sub packages (sub directories).