Pages

Some Examples of java.applet package

Displaying Image in Applet


Applet is mostly used in game and animation. For this purpose image is required to be displayed. The java.awt.Graphics class provides a method drawImage() to display the image.


How to get the object of Image:

The java.applet.Applet class provides getImage() method that returns the object of Image.

Syntax:
              public Image getImage(URL u, String image) {}

Other required methods of Applet class to display image
  • public URL getDocumentBase() : It is used to return the URL of the document in which applet is                                                            embedded.
  • public URL getCodeBase() : It is used to return the base URL.


Example of displaying image in applet

//DisplayImage.java

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

public class DisplayImage extends Applet
{
Image picture;
public void init()
{
picture = getImage(getDocumentBase(),"flower.jpg");
}

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

/*
<html>
<body>
<applet code="DisplayImage.class" width="400" height="300"></applet>
</body>
</html>
*/


Note: In the above example, drawImage() method of Graphics class is used to display the image. The 4th argument of drawImage() method of is ImageObserver object. The Component class implements Image Observer interface. So current object would also be treated as ImageObserver because Applet class indirectly extends the Component class.



Animation in Applet

Applet is mostly used in games and animation. For this purpose image is required to be moved.


Example of Animation in Applet


//AnimationDemo.java

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

public class AnimationDemo extends Applet
{
Image picture;
public void init()
{
picture = getImage(getDocumentBase(),"bbb.png");
}

public void paint(Graphics g)
{
for (int i=0;i<500 ;i++ )
{
g.drawImage(picture,i,30,this);
try
{
Thread.sleep(100);
}
catch (Exception e)
{
}
}
}
}

/*
<html>
<body>
<applet code="AnimationDemo.class" width = "1000" height = "1000"></applet>
</body>
</html>
*/



Event Handling in Applet

As we perform handling in AWT or Swing, we can perform it in applet also. Let's see the simple example of event handling in applet that prints a message by click on the button.

Example of Event Handling in Applet


// EventApplet.java

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

public class EventApplet extends Applet implements ActionListener
{
Button b;
TextField tf;

public void init()
{
tf = new TextField();
tf.setBounds(30,40,150,20);
b = new Button("Click");
b.setBounds(80,150,60,50);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}

public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome to hungry4java.blogspot.com");
}
}

/*
<html>
<body>
<applet code="EventApplet.class" width = "300" height = "300"></applet>
</body>
</html>
*/



Painting in Applet

we can perform painting operation in applet by the mouseDragged() method of MouseMotionListener.

Example of Painting in Applet by MouseMotionListener


// MouseDrag.java

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

public class MouseDrag extends Applet implements MouseMotionListener
{
public void init()
{
addMouseMotionListener(this);
setBackground(Color.green);
}

public void mouseDragged(MouseEvent me)
{
Graphics g = getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),10,10);
}

public void mouseMoved(MouseEvent me)
{}
}

/*
<html>
<body>
<applet code = "MouseDrag.class" width = "400" height= "400"></applet>
</body>
</html>
*/



Digital Clock in Applet


//DigitalClock.java

import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;

public class DigitalClock extends Applet implements Runnable
{
Thread t = null;
int hours=0, minutes=0, seconds=0;
String timeString="";

public void init()
{
setBackground(Color.green);
}

public void start()
{
t = new Thread(this);
t.start();
}

public void run()
{
try
{
while(true)
{
Calendar cal = Calendar.getInstance();
hours = cal.get(Calendar.HOUR_OF_DAY);
if(hours > 12)
hours -=12;
minutes = cal.get(Calendar.MINUTE);
seconds = cal.get(Calendar.SECOND);
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
timeString = formatter.format(date);
repaint();
t.sleep(1000);
}
}
catch (Exception e)
{
}
}

public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawString(timeString,50,50);
}
}

/*
<html>
<body>
<applet code = "DigitalClock.class" width= "300" height="300"></applet>
</body>
</html>
*/


Program which play a music


// PlaySound.java

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

public class PlaySound extends Applet implements ActionListener
{
Button play, stop;
AudioClip audioClip;

public void init()
{
play= new Button(" Play in Loop ");
add(play);
play.addActionListener(this);

stop = new Button(" Stop ");
add(stop);
stop.addActionListener(this);

audioClip = getAudioClip(getCodeBase(), "song1.wav");
}

public void actionPerformed(ActionEvent ae)
{
Button source = (Button)ae.getSource();
if(source.getLabel()==" Play in Loop ")
{
audioClip.play();
}
else if(source.getLabel()==" Stop ")
{
audioClip.stop();
}
}
}

/*
<HTML>
<BODY>
<APPLET CODE="PlaySound.class" Width="300" height="300"></APPLET>
</BODY>
</HTML>
*/



Program for an Analog Clock using Applet


//MyClock.java

import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;

public class MyClock extends Applet implements Runnable
{
int width, height;
Thread t = null;
boolean threadSuspended;
int hours = 0, minutes = 0, seconds = 0;
String timeString = "";

public void init() {
width = getSize().width; //Get the width of the applet
height = getSize().height; //Get the height of the applet
setBackground(Color.black);
}

public void start() {
if (t == null)
{
t = new Thread(this);
t.setPriority(Thread.MIN_PRIORITY);
threadSuspended = false;
t.start();
}
else {
if (threadSuspended)
{
threadSuspended = false;
synchronized(this) {
notify();
}
}
}
}

public void stop() {
threadSuspended = true;
}

public void run() {
try
{
while (true)
{
Calendar cal = Calendar.getInstance();
hours = cal.get(Calendar.HOUR_OF_DAY);
if(hours < 12)
hours -= 12;
minutes = cal.get(Calendar.MINUTE);
seconds = cal.get(Calendar.SECOND);

SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss",Locale.getDefault());
Date date = cal.getTime();
timeString = formatter.format(date);

//Now the thread checks to see if it should suspend itself
if (threadSuspended)
{
synchronized(this) {
while (threadSuspended)
{
wait();
}
}
}
repaint();
t.sleep(1000); //interval specified in milliseconds
}
}
catch (Exception e)
{
}
}

void drawHand(double angle, int radius, Graphics g) {
angle -= 0.5*Math.PI;
int x = (int)(radius*Math.cos(angle));
int y = (int)(radius*Math.sin(angle));
g.drawLine(width/2, height/2, width/2+x, height/2+y);
}

void drawWedge(double angle, int radius, Graphics g) {
angle -= 0.5*Math.PI;
int x = (int)(radius*Math.cos(angle));
int y = (int)(radius*Math.sin(angle));
angle += 2*Math.PI/3;
int x2 = (int)(5*Math.cos(angle));
int y2 = (int)(5*Math.sin(angle));
angle += 2*Math.PI/3;
int x3 = (int)(5*Math.cos(angle));
int y3 = (int)(5*Math.sin(angle));
g.drawLine(width/2+x2, height/2+y2, width/2+x, height/2+y);
g.drawLine(width/2+x3, height/2+y3, width/2+x, height/2+y);
g.drawLine(width/2+x2, height/2+y2, width/2+x3, height/2+y3);
}

public void paint (Graphics g) {
g.setColor(Color.gray);
drawWedge(2*Math.PI*hours/12, width/5,g);
drawWedge(2*Math.PI*minutes/60, width/3, g);
drawHand(2*Math.PI*seconds/60, width/2,g);
g.setColor(Color.white);
g.drawString(timeString, 10, height-10);
}
}
/*
<html>
<body>
<applet code = "MyClock.class" width = "300" height = "300"></applet>
</body>
</html>
*/



Program to communicate between two Applet

// ContextApplet.java

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

public class ContextApplet extends Applet implements ActionListener
{
Button b;
public void init() {
b = new Button("Click");
b.setBounds(50,50,60,50);
add(b);
b.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {
AppletContext ctx = getAppletContext();
Applet a = ctx.getApplet("app2");
a.setBackground(Color.red);
}
}
/*
<html>
<body>
<applet code = "ContextApplet.class" width = "150" height = "150" name = "app1"></applet>
<applet code = "First.class" width = "150" height = "150" name = "app2"></applet>
</body>
</html>
*/


// First.java

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

public class First extends Applet
{
int i = 10;
public void init() {}
}
/*
<html>
<body>
<applet code = "First.class" width = "300" height = "300"></applet>
</body>
</html>
*/

No comments:

Post a Comment