LESSON NOTE INTRO TO EVENT DRIVEN PROGRAMMING Event
driven programs are programs that run a sequence of code when an event (such
as a mouse click or a key press) occurs. To
do this in java, we simply need to include what is a called an event listener
(or just listener). A listener is an
object that is responsible for watching (listening) for events. When an event occurs, that object contains
code that is executed. INTERFACES Interfaces
are simply special classes that have a list of methods without method
bodies. Classes can then implement
interfaces and provided some or all of the functionality intended by the
interface. MOUSELISTENER INTERFACE If
you look up MouseListener in the java
documentation, you will find that it is an interface with the following
methods: void
mouseClicked(MouseEvent
e) void
mouseEntered(MouseEvent
e) void
mouseExited (MouseEvent
e) void
mousePressed(MouseEvent
e) void
mouseReleased(MouseEvent
e) We
can create an object that will listen for mouse events described by the
method names above (mouse click, mouse enters an area, mouse exits an area,
mouse pressed, mouse released). All it
has to do is implement the MouseListener
interface. Inside that class, the five
methods above must be implemented. WHO LISTENS? The
question is, which object should listen?
Should we create a separate object to do this? We can!
And it would keep things nice and neat. However,
if we want to respond to events by drawing something on the screen, we will
have to access information that is also accessible by the paint method of our
JPanel. So,
the easiest way to implement the MouseListener is
to do so in your JPanel class. Therefore, your code for the class name
will now look like this: public class AwesomePanel extends JPaneld
implements MouseListener WHAT WILL THIS LOOK LIKE? This
might seem a little messy but its
not too bad once you start working with it.
The green text shows you the new code you are adding. public
class MousePanel extends JPanel
implements MouseListener { public void
paint(Graphics g) {…} public void mouseClicked(MouseEvent e)
{…} public void mouseEntered(MouseEvent e) {…} public void mouseExited
(MouseEvent e) {…} public void mousePressed(MouseEvent e)
{…} public void mouseReleased(MouseEvent e) {…} } MOUSE EVENT You
probably noticed that every method in the MouseListener
interface has a MouseEvent argument. This is simply an object that is
automatically created that contains information about the event. The
methods you will most likely use from this object are getX() and getY() which return the x and y coordinates of the event. EXAMPLE 1 – SHOWING MOUSE EVENTS
The above code will create the
following window that will update the coordinates of different mouse
events. Of course, you need to run it
to appreciate what is happening. EXAMPLE 2 - USING CLICKS TO CHANGE PICTURES Here’s
an example that allows you to draw different information that is changed every
time the mouse is clicked.
|
||||
|
||||
|