Monday, March 9, 2015

Java using applet program



Create a banner using Applet

import java.awt.*;
import java.applet.*;
public class SampleBanner extends Applet
implements Runnable
{
   String str = "This is a simple Banner ";
   Thread t ;
   boolean b;
   public void init()
   {
      setBackground(Color.gray);
      setForeground(Color.yellow);
   }
   public void start()
   {
      t = new Thread(this);
      b = false;
      t.start();
   }
   public void run ()
   {
      char ch;
      for( ; ; )
      {
      try
      {
         repaint();
         Thread.sleep(250);
         ch = str.charAt(0);
         str = str.substring(1, str.length());
         str = str + ch;
      }
      catch(InterruptedException e) {}
      }
   }
   public void paint(Graphics g)
     {
      g.drawRect(1,1,300,150);
      g.setColor(Color.yellow);
      g.fillRect(1,1,300,150);
      g.setColor(Color.red);
      g.drawString(str, 1, 150);
   }
}

Display a clock using Applet

import java.awt.*;
import java.applet.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
public class ClockApplet extends Applet implements Runnable
{
   Thread t,t1;
   public void start()
     {
      t = new Thread(this);
      t.start();
   }
   public void run()
   {
      t1 = Thread.currentThread();
      while(t1 == t)
       {
         repaint();
         try
         {
            t1.sleep(1000);    
         }
         catch(InterruptedException e){}
      }
   }
   public void paint(Graphics g)
     {
      Calendar cal = new GregorianCalendar();
      String hour = String.valueOf(cal.get(Calendar.hour));
      String minute = String.valueOf(cal.get(Calendar.minute));
      String second = String.valueOf(cal.get(Calendar.second));
      g.drawString(hour + ":" + minute + ":" + second, 20, 30);
   }
}

Create different shapes in an Applet

import java.applet.*;
import java.awt.*;
public class  Shapes extends Applet
{
   int x=300,y=100,r=50;
   public void paint(Graphics g)
    {
      g.drawLine(30,300,200,10);
      g.drawOval(x-r,y-r,100,100);
      g.drawRect(400,50,200,100);
   }
}

No comments:

Post a Comment