JPAINT
PART  3A – DRAWING INTERACTIVITY

separator-blank

In this part, we will add the basic functionality to the canvas so that we can draw when it is clicked on.  We will not be implementing any actual tools at this moment.

DISCUSSION

We need the canvas (JPanel) to react to mouse clicks.  We do this by using a MouseListener object.  Again, we will make our JPaint class be responsible for the listening.  This will mean that we will have to implement five methods inside the class.

STEP 1

Make sure the class now also implements MouseListener.  So that line of code should be:

                public class JPaint extends JFrame implements ActionListener, MouseListener

STEP 2

Implementing MouseListener forces us to include five methods in our class.   Add the following.  Note that we will likely leave most of these blank.  We will for sure use the mouseClicked method that is automatically called when the mouse is clicked.

   public void mouseClicked(MouseEvent e)
   {
   }

   public void mouseReleased(MouseEvent e)
   {
   }

   public void mousePressed(MouseEvent e)
   {
   }

   public void mouseEntered(MouseEvent e)
   {
   }

   public void mouseExited(MouseEvent e)
   {
   }

STEP 3

We now need to add a mouseListener to our JPanel that represents the drawing canvas.  In Step 1, the guide suggested calling that JPanel ‘canvas’.  So, to add the mouseListener on canvas, we use:


     canvas.addMouseListener(this);

STEP 4

Inside the existing mouseClicked method, add a sysout statement that will output a simple message.  That message should now be displayed to console whenever you click on the canvas JPanel.

Test to make sure this works!

Continued in Part 3B…

separator-blank