Object-Oriented Programming: Computer Science Year II
Object-Oriented Programming: Computer Science Year II
Programming
Computer Science Year II
Compiled by: Mujibdheen K.
1
Java Applets
2
7.1 Overview of Java Applets
Applets are Java programs that can be embedded in Hyper Text
Markup Language (HTML) documents (i.e., Web pages). When a
browser loads a Web page containing an applet, the applet
downloads into the Web browser and executes.
The browser that executes an applet is generically known as the
applet container. The JDK includes the appletviewer applet container
for testing applets as you develop them and before you embed them
in Web pages.
Java Applets are small applications that are accessed on an Internet
server, transported over the Internet, automatically installed, and run
as part of a Web document.
3
Applet Execution
An applet is a Java program that runs within a Java-compatible WWW browser or
in an applet viewer. To execute your applet, the browser:
• Creates an instance of your applet
• Sends messages to your applet to automatically invoke predefined lifecycle methods.
The basic structure of an applet that uses each of these predefined methods is:
import java.applet.Applet;
// include all AWT class definitions
import java.awt.*;
public class AppletTemplate extends Applet {
public void init() { // create GUI, initialize applet } //Initialize Variables,
public void start() { // start threads, animations etc... } //Start/Restart
public void paint(Graphics g) { // draw things in g} //Redraw Output
public void stop() { // suspend threads, stop animations etc...} //Pause
public void destroy() { // free up system resources, stop threads } //Exit/Terminate
}
All you have to do is fill in the appropriate methods to bring your applet to life. If
you don't need to use one or more of these predefined methods, simply leave them out
of your applet. The applet will ignore messages from the browser attempting to
invoke any of these methods that you don't use.
5
Simple Java Applet: Drawing a String
The following complete applet displays "Hello, World Wide Web!" in your
browser window:
import java.applet.Applet;
import java.awt.Graphics;
public class TrivialApplet extends JApplet {
public void paint(Graphics g) {
// display a string at 20,20
// where 0,0 is the upper-left corner
g.drawString("Hello, World Wide Web!", 20, 20);
}}
Summary
1.An applet is a special type of Java program that is designed for transmission over
the Internet and that runs inside a browser.
2.The init() method is used to initialize applet instance variables…..
3.The start() method is called when an applet is started/restarted
4.The paint( ) method displays output in an applet’s window.
5.The stop() method is called when applet started is paused
6.The Destroy() method is called when applet running is terminated/exited/closed
7.The package java.applet must be included when creating an applet.
8.Applets are executed by a browser or by special tools, such as appletviewer.
6
7.2 Java Applets Vs. Java Applications
Java can be used to create two types of programs: Applications and Applets. An application
is a program that runs on your computer, under the operating systems of that computer.
An applet is an application designed to be transmitted over the Internet and executed by a
Java-Compatible Web Browser An applet is actually a tiny Java program, dynamically
downloaded across the network, just like an image, sound file,or video clip.
Java Applications – standalone (desktop) Java programs, executed from the command
line, only need the Java Virtual Machine to run.
Java Applets – Java program that runs within a Java-enabled browser, invoked
through a “applet” reference on a web page, dynamically downloaded to the client
computer.
Java Servlets – Java program running on the web server, capable of responding to
HTTP requests made through the network.
Desktop applications - Java 2 Standard Edition (J2SE)
Enterprise applications – Java 2 Enterprise Edition (J2EE)
Mobile applications – Java 2 Mobile Edition (J2ME)
Smart card applications – JavaCard
7
.
// WelcomeApplet.java
// A first applet in Java.
import java.awt.Graphics; // program uses class Graphics
import javax.swing.JApplet; // program uses class JApplet
9
<param name=p2 value="test">
</applet>
where p1 and p2 are user-defined parameters.
The code, width, and height parameters are mandatory. The parameters
codebase, alt, archives, align, vspace, and hspace are optional within the
<applet> tag itself. Your applet can access any of these parameters by calling:
Applet.getParameter("p")
which returns the String value of the parameter. For example, the applet:
import java.applet.Applet;
public class ParamTest extends Applet {
public void init() {
System.out.println("width is " + getParameter("width"));
System.out.println("p1 is " + getParameter("p1"));
System.out.println("p2 is " + getParameter("p2"));
}
}
prints the following to standard output:
width is 300
p1 is 34
p2 is test 10
.
3. In the dialog box that appears, locate the directory containing the HTML document for
the applet you wish to execute.
[Note: The steps for executing applets in other Web browsers are similar.]
11
// AdditionApplet.java
* .
13
//Following
. example demonstrates how to display a
clock using valueOf() mehtods of String Class. public void paint(Graphics g) {
//& using Calender class to get the second, minutes &
Calendar cal = new GregorianCalendar();
hours.
import java.applet.*;
String hour = String.valueOf(cal.get(Calendar.HOUR));
import java.awt.*;
import java.util.*;
String minute =
public class ClockApplet extends Applet implements String.valueOf(cal.get(Calendar.MINUTE));
Runnable {
String second =
Font f = new Font("Segeo Condensed", Font.BOLD, 20);
Thread t, t1; String.valueOf(cal.get(Calendar.SECOND));
public void start() {
t = new Thread(this); g.setFont(f);
t.start();
} g.drawString("Current Time: " + hour + ":" + minute
public void run() {
t1 = Thread.currentThread(); + ":" + second, 330, 25);
while (t1 == t) {
repaint(); showStatus("Displaying Current Time.");
try {
t1.sleep(1000); setForeground(Color.black);
} catch (InterruptedException e) {
} setBackground(Color.orange);
}
} 14 setSize(600, 300);
//To display an image in an applet we first need to
.
/Following example demonstrates how to obtain the image object itself. A call to applet's
display image using getImage() method. It getImage(URL url, String name) method help us to
also uses addImage() method of create an image object from the specified URL of
MediaTracker class. the image.
//For displaying the image on the applet's screen we
import java.awt.*; draw it in the paint() method using
import javax.swing.JApplet; Graphics.drawImage() method.
public class AppletImage extends JApplet { import java.awt.*;
Image img; import javax.swing.JApplet;
public class AppletGetImage extends JApplet {
MediaTracker tr;
private Image logo;
public void paint(Graphics g) {
public void init() {
tr = new MediaTracker(this); // Get an Image object that can be painted on
img = getImage(getCodeBase(), "M2.jpg");
the //Applet screen. We need to supply the URL
tr.addImage(img,0); of the //document as the base location of the image
g.drawImage(img, 10, 10, this); and the //location of image relative the the base
showStatus("Displaying Image on Applets.");
URL.
setSize(680,380); logo =
} getImage(getDocumentBase(),"Images/M2.jpg");
} }
Media Tracker - Creates a media tracker public void paint(Graphics g) {
to track images for a given component. g.drawRect(0, 0, getWidth() - 1, getHeight() -
1);
15
g.drawImage(logo, 20, 20, this);
//This is a simple text clock. See javax.swing.Timer for an explanation of content.add(timeField);
. use //this simple timer class.
how this.setTitle("Text Clock");
import java.awt.*; setResizable(false);
import java.awt.event.*; timeField.setEditable(false);
import java.util.Calendar; setLocationRelativeTo(null);
import javax.swing.*; this.pack();
/// TextClock // Create a 1-second timer and action listener for it.
public class TextClock { // Specify package because there are two Timer classes
//main javax.swing.Timer t = new javax.swing.Timer(1000,new
public static void main(String[] args) { ActionListener() {
JFrame clock = new TextClockWindow(); @Override
clock.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); public void actionPerformed(ActionEvent e) {
clock.setVisible(true); Calendar now = Calendar.getInstance();
}//end main int h =
}//endclass TextClock now.get(Calendar.HOUR_OF_DAY);
////// TextClockWindow int m = now.get(Calendar.MINUTE);
class TextClockWindow extends JFrame { int s = now.get(Calendar.SECOND);
//instance variables timeField.setText("" + h + ":" + m + ":" + s);
private JTextField timeField; // set by timer listener }
//constructor });
public TextClockWindow() { t.start(); // Start the timer
// Build the GUI - only one panel }//end constructor
timeField = new JTextField(5); }//endclass TextClock
timeField.setFont(new Font("Segeo Condensed",
Font.BOLD, 60));
timeField.setForeground(Color.red);
timeField.setBackground(Color.CYAN);
Container content = this.getContentPane();
content.setLayout(new FlowLayout()); 16
input = new TextField(7);
.
//Following example demonstrates how to go use add(input);
Swing Applet in JAVA by implementing label2 = new Label("Sum : ");
add(label2);
ActionListener & by creating JLabels. label2.setBackground(Color.yellow);
label2.setForeground(Color.magenta);
import java.applet.*; output = new TextField(7);
import java.awt.*; add(output);
import java.awt.event.*; b1 = new Button("Add");
add(b1);
import javax.swing.*; b1.addActionListener(this);
lbl = new JLabel("Swing Applet Example. ");
public class SumApplet extends Applet add(lbl);
implements ActionListener { setBackground(Color.yellow);
TextField input,output; }
public void actionPerformed(ActionEvent ae){
Label label1,label2; try{
Button b1; num = Integer.parseInt(input.getText());
JLabel lbl; sum = sum+num;
int num, sum = 0; input.setText("");
public void init(){ output.setText(Integer.toString(sum));
lbl.setForeground(Color.blue);
label1 = new Label("Numbers: "); lbl.setText("The Sum: "+ output.getText());
add(label1); }
label1.setBackground(Color.yellow); catch(NumberFormatException e){
label1.setForeground(Color.magenta); lbl.setForeground(Color.red);
17 lbl.setText("Invalid Entry!");
}}}
/* A simple banner applet.
// Entry point for the thread that runs the banner.
This
. applet creates a thread that scrolls
the message contained in msg right to left public void run() {
across the applet's window. char ch;
*/ // Display banner
import java.awt.*; for( ; ; ) {
import java.applet.*; try {
/* repaint();
<applet code="SimpleBanner" width=300 height=50> Thread.sleep(250);
</applet> ch = msg.charAt(0);
*/
msg = msg.substring(1, msg.length());
public class SimpleBanner extends Applet implements
msg += ch;
Runnable {
if(stopFlag)
String msg = " A Simple Moving Banner.";
break;
Thread t = null;
} catch(InterruptedException e) {}
int state;
}
boolean stopFlag;
}
public void init() {
// Pause the banner.
setBackground(Color.cyan); // Set colors and initialize
public void stop() {
thread.
stopFlag = true;
setForeground(Color.red);
t = null;
}
}
public void start() {// Start thread
// Display the banner.
t = new Thread(this);
public void paint(Graphics g) {
stopFlag = false;
g.drawString(msg, 50, 30);
t.start();
} 18
}
}