Tuesday, February 25, 2014

Java Animation (Mouse Events)

import java.applet.Applet;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Date;
import java.awt.*;
import java.awt.event.*;



             /*<applet code="DigitalClock" width=800 height=800>
             </applet>*/

public class DigitalClock extends Applet
    implements Runnable,MouseMotionListener ,MouseListener
{

    Font theFont;
    Date theDate;
    Thread runner;
    int x1;
    int y1;
    int x2;
    int y2;
    int cx1;
    int cy1;
    int cx2;
    int cy2;

    public DigitalClock()
    {
        theFont = new Font("TimesRoman", 1, 24);
    }

    public void init()
    {
        x1 = 100;
        y1 = 100;
        x2 = 150;
        y2 = 100;
 this.addMouseMotionListener(this);
this.addMouseListener(this);

    }

public void mouseMoved(MouseEvent event){

      setBackground(Color.red);

}

public void mouseDragged(MouseEvent event){

      setBackground(Color.cyan);

}
public void mouseClicked(MouseEvent e){

if (e.getButton() == MouseEvent.BUTTON1)
{
   runner.stop();
      runner = null;     
}
if (e.getButton() == MouseEvent.BUTTON3)
{

           runner = new Thread(this);
            runner.start();
}

 
      setBackground(Color.blue);

}

public void mouseEntered(MouseEvent e){

      setBackground(Color.cyan);

}

public void mouseExited(MouseEvent e){

      setBackground(Color.green);

}

public void mousePressed(MouseEvent e){

      setBackground(Color.magenta);

}

public void mouseReleased(MouseEvent e){

      setBackground(Color.yellow);

}
    public void start()
    {
        if(runner == null)
        {
            runner = new Thread(this);
            runner.start();
        }
    }

    public void stop()
    {
        if(runner != null)
        {
            runner.stop();
            runner = null;
        }
    }

    public void run()
    {
        do
        {
            theDate = new Date();
            x1 = x1 + 100;
            x2 = x2 + 100;
            if(x2 > 1000)
            {
                x2 = 150;
                x1 = 100;
            }
            repaint();
            try
            {
                Thread.sleep(200L);
            }
            catch(InterruptedException interruptedexception) { }
        } while(true);
    }

    public void paint(Graphics g)
    {
        g.drawLine(x1, y1, x2, y2);
        g.drawOval(x1, y1, x2, y2);
        g.setFont(theFont);
        g.drawString(theDate.toString(), 10, 50);
    }
}

No comments: