advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement


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.

 Microsoft Visual Studio 2010 Showcase
 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 39
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Windows 7: From Beta to Final Code in One Year
Google Shows Off Chrome OS, Releases Source
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?
Fedora 12 Takes Aim at Linux Networking
Top Supercomputer Nearly Doubles in Speed
Fedora 12 Linux Tackles Virtualization
Apple Gives iPhone Developers App Status Tracker
Novell Sets OpenSUSE 11.2 Free

Creating Custom Export Filters for StarOffice with XSLT
WPF Wonders: Using DataTemplates
Crystal Reports Family Offers Options for Developers
Avaya Aura Session Manager video
Avaya Aura Overview video
Exploring HTML 5's Audio/Video Multimedia Support
Overriding Virtual Functions? Use C++0x Attributes to Avoid Bugs.
Understanding the Cloud Computing Security Vulnerabilities
Cisco and IBM Target a Greener World
Upgrade to Visual Studio 2010 with the Ultimate Offer

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs