Tutorials : Java by Example : Section 6 :
Section Six Contents
Using Mousemove and Mousedrag
Keyboard Commands and Playing Sound
Detecting Collisions and Intersections
A Bouncing Balls Applet

Input Devices

Using Mousemove and Mousedrag

This applet enhances our last one, by making the colored boxes objects of a self-defined class SwitchRectangle. This class features the possibility to change the colors of the rectangles by clicking at them. The current color of the three SwitchRectangle objects is also reported back, to enable drawing the correct color name. The colors are represented by three constant integer variables, which are declared as static final in Java. Such variables must be initialized with a value at the same time they are declared and cannot accidentally be changed during program runtime. In this program I used expressions like if(inside) instead of if(inside==true) and if(!inside) instead of if(inside==false) (inside being a boolean variable). This is shorter and you should get accustomed to use it yourself. Study the sourcecode carefully, even though it might seem like child's play to you. Small examples like this quickly enable you to succeed in bigger projects.

//Sourcecode

import java.awt.*;
import java.applet.*;

class SwitchRectangle
{
        public Rectangle r=new Rectangle();
        private int color;
        //we declare 3 int variables to store color values here
        //"static final" are constant variables that must not be changed
        //they have to be initialized at the same time they are declared!
        static final int RED=1;
        static final int GREEN=2;
        static final int BLUE=3;
        private boolean inside;
        Graphics g;

        //our constructor, it initializes the rectangle coordinates and color
        public SwitchRectangle(int x, int y, int w, int h, int color)
        {
                r.x=x;
                r.y=y;
                r.width=w;
                r.height=h;
                this.color=color;
        }

        //if mouse is moved inside our rectangle, the flag "inside" is set
        public void SubmitMouseCoord(int x, int y)
        {
                if(r.inside(x, y))
                        inside=true;
                else
                        inside=false;
        }

        public void switchColor(int x, int y)
        {
                if(r.inside(x, y))
                {
                        if(color<BLUE)
                                color++;
                        else
                                color=RED;
                }
        }

        //a method that is not of type void has to return a value.
        //the key word "else" is not neccessary here, but can be used
        public int getColor()
        {
                //if the mouse cursor is not inside our rectangle,
                //we return 0, otherwise the active color variable value
                if(!inside)
                        return 0;
                else
                        return color;
        }

        public void paint(Graphics gr)
        {
                g=gr;

                if(color==RED)
                        g.setColor(Color.red);

                else if(color==GREEN)
                        g.setColor(Color.green);

                else
                        g.setColor(Color.blue);

                g.fillRect(r.x, r.y, r.width, r.height);

                if(inside)
                {
                        g.setColor(Color.white);
                        g.drawRect(r.x, r.y, r.width-1, r.height-1);
                }
        }
}

public class Project28 extends Applet
{
       Image Buffer;
       Graphics gBuffer;
       int x, y;
       boolean mouseInside, insideRed, insideGreen, insideBlue;
       SwitchRectangle sr1, sr2, sr3;
       //the constant color variables have to be declared here too!
       static final int RED=1;
       static final int GREEN=2;
       static final int BLUE=3;

       public void init()
       {
             Buffer=createImage(size().width,size().height);
             gBuffer=Buffer.getGraphics();

             //create 3 objects of our SwitchRectangle class
             sr1=new SwitchRectangle(20,70,80,100,RED);
             sr2=new SwitchRectangle(110,70,80,100,GREEN);
             sr3=new SwitchRectangle(200,70,80,100,BLUE);
        }

        public void drawStuff()
        {
             gBuffer.setColor(Color.black);
             gBuffer.fillRect(0,0,size().width,size().height);

             //paint the 3 rectangles
             sr1.paint(gBuffer);
             sr2.paint(gBuffer);
             sr3.paint(gBuffer);

             //draw the mouse coordinates
             if (mouseInside)
             {
                  gBuffer.setFont(new Font("Helvetica",Font.BOLD,12));
                  gBuffer.setColor(Color.white);
                  gBuffer.drawString ("X:  "+x,30,30);
                  gBuffer.drawString ("Y:  "+y,30,50);
             }
             else
             {
                  gBuffer.setFont(new Font("Helvetica",Font.PLAIN,14));
                  gBuffer.setColor(Color.orange);
                  gBuffer.drawString ("Click the three rectangles!",70,30);
             }

             //since we need this font several times, we create it here
             Font bigFont=new Font("Helvetica",Font.BOLD,45);

             if (insideRed)
             {
                  gBuffer.setFont(bigFont);
                  gBuffer.setColor(Color.red);
                  gBuffer.drawString ("Red",120,50);
             }

             if (insideGreen)
             {
                  gBuffer.setFont(bigFont);
                  gBuffer.setColor(Color.green);
                  gBuffer.drawString ("Green",120,50);
             }

             if (insideBlue)
             {
                  gBuffer.setFont(bigFont);
                  gBuffer.setColor(Color.blue);
                  gBuffer.drawString ("Blue",120,50);
             }
        }

        //detects any mouse move within our applet
        public boolean mouseMove(Event evt,int x,int y)
        {
                //submit the mouse coordinates to our instance variables
                this.x=x;
                this.y=y;

                sr1.SubmitMouseCoord(x, y);
                sr2.SubmitMouseCoord(x, y);
                sr3.SubmitMouseCoord(x, y);

                detectColor();

                repaint();
                return true;
                }

                public boolean mouseEnter(Event evt,int x,int y)
                {
                        mouseInside=true;
                        return true;
                }

                public boolean mouseExit(Event evt,int x,int y)
                {
                        mouseInside=false;
                        repaint(500);
                        return true;
                }

                public boolean mouseDown(Event evt,int x,int y)
                {
                        sr1.switchColor(x, y);
                        sr2.switchColor(x, y);
                        sr3.switchColor(x, y);

                        detectColor();

                        repaint();
                        return true;
                }

                //this method detects the color that's under the mouse cursor,
                //to tell if it's "Red", "Green" or "Blue"
                void detectColor()
                {
                    //if one of our 3 SwitchingRectangles reports RED, we set the flag
                    //"insideRed" to true, otherwise to false
                    if(sr1.getColor()==RED||sr2.getColor()==RED||sr3.getColor()==RED)
                          insideRed=true;
                    else
                          insideRed=false;

                    if(sr1.getColor()==GREEN||sr2.getColor()==GREEN||sr3.getColor()==GREEN)
                          insideGreen=true;
                    else
                          insideGreen=false;

                    if(sr1.getColor()==BLUE||sr2.getColor()==BLUE||sr3.getColor()==BLUE)
                          insideBlue=true;
                    else
                          insideBlue=false;
                }

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

   public void paint(Graphics g)
        {
                drawStuff();
                g.drawImage (Buffer,0,0, this);
        }
}

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.