Java

Applet Examples

Creating first java applet program to display simple strings.

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

/*<applet code=app.class width=200 height=200> </applet> 

*/

public class app extends Applet
{
String str,str2;

public void init()
{
str="Hello to applet Programming";
str2="Hello to applet Programming";
}
public void paint(Graphics g)
{
g.drawString(str, 10, 10);
g.drawString(str2, 10, 30);
g.drawString("hello to MIT India", 10, 50);
}
}

Applet program to display an image.

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

/*<applet code=app2.class width=200 height=200> </applet> */
public class app2 extends Applet
{
Image img;

public void init()
{
img=getImage(getCodeBase(), "login.png");
}

public void paint(Graphics g)
{
g.drawImage(img, 10, 20, this);
}
}

Java Applet program to display SUM of Two numbers.

import java.awt.*;
import java.applet.*;
/* <applet code=app3.class width=200 height=200> 

</applet> */
public class app3 extends Applet
{
int a,b,c;
String str;
public void init()
{
a=3; 
b=5; 
c=a+b;
str="Sum of a and b is : " + String.valueOf(c);
}
public void paint(Graphics g)
{
g.drawString(str, 10, 20);
}
}

Applet program to show graphic demo. [drawing rectangle and filling it with colors]

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

/*<applet code="App5.class" width=300 height=200> 

</applet> */
public class App5 extends Applet{

    
    public void paint(Graphics g)
    {
        String str="Applet Test!";
        g.drawString(str, 10, 20);
        
        g.setColor(Color.RED);
        g.fillRect(10, 20, 50, 50);
        g.drawRect(10, 20, 50, 50);
        
        g.setColor(Color.BLUE);
        g.fillRect(10, 80, 50, 50);
        g.drawRect(10, 80, 50, 50);
        
        g.setColor(Color.GREEN);
        g.fillRect(10, 140, 50, 50);
        g.drawRect(10, 140, 50, 50);
        }
}

Applet program to show simple scrolling banner.

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

/* <APPLET ALIGN="CENTER" CODE="banner.class" WIDTH="300" HEIGHT="400"></APPLET> */

public class banner 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);
  }
}
SKB