Java and Distance Education 3

William Overington

Copyright 2000 William Overington

Starting to use the mouse.

Using the mouse falls into two distinct parts. The mouse can trigger seven functions. Five of these functions are triggered using MouseListener and two of these functions are triggered using MouseMotionListener. In using the mouse, one may use either the set of five functions, or the set of two functions, or all seven functions together if one wishes. The reason for this is that the two functions which are triggered by MouseMotionListener are caused by moving the mouse and by dragging the mouse, (that is, moving the mouse with a button depressed) are triggered a lot more often than the five functions which are triggered by MouseListener. The design feature of having two different listeners for one mouse means that if one does not need to have one's program responding to mouse moves and mouse drags, then one need not include the MouseMotionListener and the two functions that it triggers and so the computer does not need to spend any time dealing with mouse moves and mouse drags. In this section of the course we are using MouseListener and not using MouseMotionListener. We need to include all five functions, even though, in this example, we are using only one of them to do anything.

Please consider the program that follows. It is based on the program in section 1 of this course. In section 1 there were two buttons. Here there are six square areas of colour.

The program at start up.

Clicking on any one of those six squares of colour will produce a random line using the colour of that square. The word clicking is used here, yet as will be seen, in this program the response is to the mouse button being pressed down. However, this is only because the area of colour is placed at startup, using the software in the paint function for when obeycode equals 1, in the same place as where the software in the paint function for when obeycode equals 41 reacts to a mouse button press. Clearly, with the feedback loop of a user looking at the screen, using the mouse and expecting to see a coloured line drawn on the screen, such an arrangement is simply sensible. Yet please understand that it is an arrangement, a careful arrangement of programming. It is not that the colour where the mouse is clicked is, say, red that causes the line to be drawn in red, as if the software were reading in the colour off the screen when the mouse were clicked and then using the colour that were read. Even if the six coloured squares were not drawn onto the screen at startup the coloured random lines would still be drawn when the mouse were in the correct place and a mouse button were pressed. The problem for the user would be estimating where the mouse should be positioned in order for a pressing of a mouse button to have a desired effect.

The program after one press of the mouse button when the mouse pointer is on the yellow square. The line is random and a different run will extremely likely produce a different result.

import java.awt.*;
import java.awt.event.*;

public class Applet3 extends java.applet.Applet
                             implements MouseListener
  {
    int obeycode = 1;
    int xzero = 140;
    int yzero = 40;
    int pressx,pressy;

    public void init()
      {
        setBackground(Color.darkGray);
        setLayout(null);
        setBounds(0,0,500,300);
        addMouseListener(this);
      }

    public void mousePressed(MouseEvent e)
      {
        obeycode=41;
        pressx=e.getX();
        pressy=e.getY();
        repaint();
      }

    public void mouseReleased(MouseEvent e)
      {

      }

    public void mouseClicked(MouseEvent e)
      {

      }

    public void mouseEntered(MouseEvent e)
      {
       
      }

    public void mouseExited(MouseEvent e)
      {
       
      }

    public void paint(Graphics screen)
      {
        if(obeycode == 1)
          {
            screen.setColor(Color.red);
            screen.fillRect(20,90,20,20);
            screen.setColor(Color.orange);
            screen.fillRect(20,110,20,20);
            screen.setColor(Color.yellow);
            screen.fillRect(20,130,20,20);
            screen.setColor(Color.green);
            screen.fillRect(20,150,20,20);
            screen.setColor(Color.blue);
            screen.fillRect(20,170,20,20);
            screen.setColor(Color.magenta);
            screen.fillRect(20,190,20,20);
          }

        if(obeycode == 41)
          {
            double d1,d2,d3,d4;
            int x1,y1,x2,y2;
            d1=220.0*Math.random();
            x1=(int)d1;
            d2=220.0*Math.random();
            y1=(int)d2;
            d3=220.0*Math.random();
            x2=(int)d3;
            d4=220.0*Math.random();
            y2=(int)d4;
            if ((pressx >= 20) & (pressx < 40) &
                     (pressy >= 90) & (pressy < 210))
            // The & symbol means AND
              {
                if (pressy < 110)
                  {
                    screen.setColor(Color.red);
                  }
                else if (pressy < 130)
                  {
                    screen.setColor(Color.orange);
                  }
                else if (pressy < 150)
                  {
                    screen.setColor(Color.yellow);
                  }
                else if (pressy < 170)
                  {
                    screen.setColor(Color.green);
                  }
                else if (pressy < 190)
                  {
                    screen.setColor(Color.blue);
                  }
                else if (pressy < 210)
                  {
                    screen.setColor(Color.magenta);
                  }
                screen.drawLine(xzero+x1,yzero+y1,xzero+x2,yzero+y2);
              }
          }
           
      }

    public void update(Graphics screen)
      {
        paint(screen);
      }

  }

Please run the program using the following HTML file, giving it a name of Applet3.htm or some name of your choice, for the name of the HTML file does not affect the running of the applet.

<html>
<head>
</head>
<body bgcolor="#808000">
<p align=center> 
<applet code="Applet3.class" width=500 height=300> 
</applet>
</body>
</html>

When the program is running, please click on each of the coloured squares in whatever order you wish, clicking on some several times in succession. Please notice how coloured lines are generated on the screen, of random location and size within the chosen square display area. Also, please click elsewhere on the background of the applet and observe that nothing happens.

Remember that previously it was mentioned that in this program the response is to the mouse button being pressed down rather than the response being to the mouse button being clicked as such. In order to observe the difference, please press on the mouse button while the mouse pointer is over one of the coloured squares and hold the mouse button down. Please note that the line is drawn, even though the mouse has not been clicked. A click can involve pressing and releasing within a time interval and so I find it preferable to have the software respond to the press of the button rather than the click as such, unless there is some reason for doing otherwise. This though is something of my own programming style.

While the program is running, please press down the shift key of the keyboard and click on the red square while the shift key is held down. Please note that a line is drawn on the screen exactly the same as if the shift key had not been held down. This is for the sake of completeness for the next part of this section of the course where the program is altered so that the holding down of the shift key while the mouse is clicked will have an effect. Please now consider this next version of the program. It is not the final version but is a development stage as I would like to demonstrate something to you.

import java.awt.*;
import java.awt.event.*;

public class Applet3 extends java.applet.Applet
                             implements MouseListener
  {
    int obeycode = 1;
    int xzero = 140;
    int yzero = 40;
    int pressx,pressy;
    boolean thickline;

    public void init()
      {
        setBackground(Color.darkGray);
        setLayout(null);
        setBounds(0,0,500,300);
        addMouseListener(this);
      }

    public void mousePressed(MouseEvent e)
      {
        obeycode=41;
        pressx=e.getX();
        pressy=e.getY();
        thickline=e.isShiftDown();
        repaint();
      }

    public void mouseReleased(MouseEvent e)
      {

      }

    public void mouseClicked(MouseEvent e)
      {

      }

    public void mouseEntered(MouseEvent e)
      {
       
      }

    public void mouseExited(MouseEvent e)
      {
       
      }

    public void paint(Graphics screen)
      {
        if(obeycode == 1)
          {
            screen.setColor(Color.red);
            screen.fillRect(20,90,20,20);
            screen.setColor(Color.orange);
            screen.fillRect(20,110,20,20);
            screen.setColor(Color.yellow);
            screen.fillRect(20,130,20,20);
            screen.setColor(Color.green);
            screen.fillRect(20,150,20,20);
            screen.setColor(Color.blue);
            screen.fillRect(20,170,20,20);
            screen.setColor(Color.magenta);
            screen.fillRect(20,190,20,20);
          }

        if(obeycode == 41)
          {
            double d1,d2,d3,d4;
            int x1,y1,x2,y2;
            d1=220.0*Math.random();
            x1=(int)d1;
            d2=220.0*Math.random();
            y1=(int)d2;
            d3=220.0*Math.random();
            x2=(int)d3;
            d4=220.0*Math.random();
            y2=(int)d4;
            if ((pressx >= 20) & (pressx < 40) &
                     (pressy >= 90) & (pressy < 210))
            // The & symbol means AND
              {
                if (pressy < 110)
                  {
                    screen.setColor(Color.red);
                  }
                else if (pressy < 130)
                  {
                    screen.setColor(Color.orange);
                  }
                else if (pressy < 150)
                  {
                    screen.setColor(Color.yellow);
                  }
                else if (pressy < 170)
                  {
                    screen.setColor(Color.green);
                  }
                else if (pressy < 190)
                  {
                    screen.setColor(Color.blue);
                  }
                else if (pressy < 210)
                  {
                    screen.setColor(Color.magenta);
                  }
                
                if (thickline)
                  {
                    for(int i=-10; i <= 10; i=i+10)
                      {
                        for(int j=-10; j <= 10; j=j+10)
                          {            
                            screen.drawLine(xzero+x1+i,yzero+y1+j,
                                              xzero+x2+i,yzero+y2+j);
                          }
                      }
                  }
                else
                  {
                    screen.drawLine(xzero+x1,yzero+y1,
                                      xzero+x2,yzero+y2);
                  }
              }
          }
           
      }

    public void update(Graphics screen)
      {
        paint(screen);
      }

  }

Please note the addition of

boolean thickline;

in the declarations. Please note the addition of

thickline=e.isShiftDown();

in the mousePressed function. The paint function has the line

screen.drawLine(xzero+x1,yzero+y1,xzero+x2,yzero+y2);

replaced by the following sequence, which includes the original line, such that the original line is obeyed if the shift key is not held down when the mouse button is pressed and that nine lines are drawn if the shift key is held down when the mouse button is pressed. The original line has now been placed onto two lines of the source code. This is simply so that this section of learning material will be displayed without a horizontal scrollbar appearing at the bottom of the page due to the length of the line of software, bearing in mind that in this program the original line has been indented a number of character positions to the right as a result of the introduction of the if statement.

if (thickline)
  {
    for(int i=-10; i <= 10; i=i+10)
      {
        for(int j=-10; j <= 10; j=j+10)
          {            
            screen.drawLine(xzero+x1+i,yzero+y1+j,
                              xzero+x2+i,yzero+y2+j);
          }
      }
  }
else
  {
    screen.drawLine(xzero+x1,yzero+y1,
                      xzero+x2,yzero+y2);
  }

Please note that I have chosen to name the boolean variable thickline so that when someone is reading the software the meaning is more obvious. However, I could have chosen a name such as apple for it had I so chosen and the software would have run the same. Occasionally some learners form an idea that, applied to this program, would be that the computer somehow knows that a thick line is intended because the name thickline is used as a variable name. I feel that it is important to mention this just in case a learner gets this idea into his or her mind and starts to misunderstand. The choice of the name thickline is simply to help readers of the software understand its meaning.

Please compile and run the program. Firstly, click on one of the coloured squares without the shift key held down to assure yourself that the program works as it did originally when the shift key is not pressed down. Now, please hold down the shift key and click on the yellow square. Depending on the angle that the lines make on the screen, nine, three or five lines may appear.

The program after a click with the shift key held down. Please note that nine distinct lines are shown.

Lines that are approximately vertical will appear as three lines, lines that are approximately horizontal will appear as three lines, lines at approximately 45 degrees to the horizontal will appear as five lines. Lines at other angles will appear as nine lines, the way that they are separated depending upon the angle. Where less than nine lines appear, this is because some lines are drawn on top of other lines.

The program after a click with the shift key held down. Here the nine lines are drawn with some lines on top of others, giving the appearance of only three lines being present.

The program after a click with the shift key held down. Here the nine lines are drawn with some lines on top of others, giving the appearance of only five lines being present.

Please click various colour squares a few times with the shift key held down to gain experience of how the nine lines appear. Please note how the starting points of the nine lines are on a grid of points with the grid points at a ten pixel spacing.

Having gained this experience, the final version of the program is presented, with the starting points of the nine lines on a grid of points with the grid points at a one pixel spacing.

import java.awt.*;
import java.awt.event.*;

public class Applet3 extends java.applet.Applet
                             implements MouseListener
  {
    int obeycode = 1;
    int xzero = 140;
    int yzero = 40;
    int pressx,pressy;
    boolean thickline;

    public void init()
      {
        setBackground(Color.darkGray);
        setLayout(null);
        setBounds(0,0,500,300);
        addMouseListener(this);
      }

    public void mousePressed(MouseEvent e)
      {
        obeycode=41;
        pressx=e.getX();
        pressy=e.getY();
        thickline=e.isShiftDown();
        repaint();
      }

    public void mouseReleased(MouseEvent e)
      {

      }

    public void mouseClicked(MouseEvent e)
      {

      }

    public void mouseEntered(MouseEvent e)
      {
       
      }

    public void mouseExited(MouseEvent e)
      {
       
      }

    public void paint(Graphics screen)
      {
        if(obeycode == 1)
          {
            screen.setColor(Color.red);
            screen.fillRect(20,90,20,20);
            screen.setColor(Color.orange);
            screen.fillRect(20,110,20,20);
            screen.setColor(Color.yellow);
            screen.fillRect(20,130,20,20);
            screen.setColor(Color.green);
            screen.fillRect(20,150,20,20);
            screen.setColor(Color.blue);
            screen.fillRect(20,170,20,20);
            screen.setColor(Color.magenta);
            screen.fillRect(20,190,20,20);
          }

        if(obeycode == 41)
          {
            double d1,d2,d3,d4;
            int x1,y1,x2,y2;
            d1=220.0*Math.random();
            x1=(int)d1;
            d2=220.0*Math.random();
            y1=(int)d2;
            d3=220.0*Math.random();
            x2=(int)d3;
            d4=220.0*Math.random();
            y2=(int)d4;
            if ((pressx >= 20) & (pressx < 40) &
                     (pressy >= 90) & (pressy < 210))
            // The & symbol means AND
              {
                if (pressy < 110)
                  {
                    screen.setColor(Color.red);
                  }
                else if (pressy < 130)
                  {
                    screen.setColor(Color.orange);
                  }
                else if (pressy < 150)
                  {
                    screen.setColor(Color.yellow);
                  }
                else if (pressy < 170)
                  {
                    screen.setColor(Color.green);
                  }
                else if (pressy < 190)
                  {
                    screen.setColor(Color.blue);
                  }
                else if (pressy < 210)
                  {
                    screen.setColor(Color.magenta);
                  }
                
                if (thickline)
                  {
                    for(int i=-1; i <= 1; i++)
                      {
                        for(int j=-1; j <= 1; j++)
                          {            
                            screen.drawLine(xzero+x1+i,yzero+y1+j,
                                              xzero+x2+i,yzero+y2+j);
                          }
                      }
                  }
                else
                  {
                    screen.drawLine(xzero+x1,yzero+y1,
                                      xzero+x2,yzero+y2);
                  }
              }
          }
           
      }

    public void update(Graphics screen)
      {
        paint(screen);
      }

  }

Please compile and run the program.

Several lines drawn using the final program, some with the shift key held down.

Please notice that the only changes that have been made are in the two for statements. Please remember that

i++

is a convenient short form for writing

i=i+1

and that it is not followed by a ; character here in the for statement as the ; character is used to separate statements, even though it is placed at the end of one statement and looks like it is part of that statement. If this convenient short form were used in the ordinary sequence of statements in a program, then the form

i++;

would be used. Please know that as well as the boolean function isShiftDown(), one also has isControlDown() and isAltDown() available so that one can make a program respond to various combinations of the shift, control and alt keys as one chooses. However, I do not recommend a function that requires holding down more than two of these keys while the mouse button is clicked. It may well be best to try to avoid requiring users to hold down more than one key at a time in order for a program to work. For example, a checkbox on the screen might be a better way for a user to be asked to signal some particular combination of circumstances rather than ask the user to hold down two keys while clicking the mouse. Or, if one wishes to have a screen display which does not contain any on screen components, one might have a square near the corner of the screen in, say, white, where clicking upon it causes both the square to be displayed in cyan and a boolean variable in the program which had its value set at false at start up of the program to have its value set as true. This could be reset by clicking upon the cyan square, which would then become displayed in white again.

Java and Distance Education index page.

Java and Distance Education

Copyright 2000 William Overington