0% found this document useful (0 votes)
52 views18 pages

Object-Oriented Programming: Computer Science Year II

1. Java applets allow Java programs to be embedded into HTML pages and run within web browsers. 2. When a web page containing an applet is loaded, the applet downloads and its predefined lifecycle methods like init(), start(), paint(), stop(), and destroy() are automatically called. 3. The init() method initializes the applet, start() starts animations/threads, paint() redraws the output, stop() suspends animations/threads, and destroy() performs cleanup.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
52 views18 pages

Object-Oriented Programming: Computer Science Year II

1. Java applets allow Java programs to be embedded into HTML pages and run within web browsers. 2. When a web page containing an applet is loaded, the applet downloads and its predefined lifecycle methods like init(), start(), paint(), stop(), and destroy() are automatically called. 3. The init() method initializes the applet, start() starts animations/threads, paint() redraws the output, stop() suspends animations/threads, and destroy() performs cleanup.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 18

Object-Oriented

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 predefined methods automatically invoked by the runtime system are:


 init(). This method takes the place of the Applet constructor and is only called
once during applet creation. Instance variables should be initialized in this method.
GUI components such as buttons and scrollbars should be added to the GUI in
this method.
 start(). This method is called once after init() and whenever your applet is revisited
by your browser, or when you deiconify your browser. This method should be used to
start animations and other threads.
 paint(Graphics g). This method is called when the applet drawing area needs to be
redrawn. Anything not drawn by contained components must be drawn in this method.
Bitmaps, for example, are drawn here, but buttons are not because they handle their own
painting.
 stop(). This method is called when you leave an applet or when you iconify your
browser. The method should be used to suspend animations and other threads so they do
not burden system resources unnecessarily. It 4is guaranteed to be called before destroy().
destroy(). This method is called when an applet terminates, for example, when quitting
the browser. Final clean-up operations such as freeing up system resources with dispose()
should be done here. The dispose() method of Frame removes the menu bar. Therefore, do
not forget to call super.dispose() if you override the default behavior.

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

public class WelcomeApplet extends JApplet {


// draw text on applet's background
public void paint( Graphics g ) {
// call superclass version of method paint
super.paint( g );
// draw a String at x-coordinate 25 and y-coordinate 25
g.drawString( "Welcome to Java Programming!", 25, 25 );
} // end method paint
} // end class WelcomeApplet

WelcomeApplet.html loads WelcomeApplet


<html>
<applet code = "WelcomeApplet.class" width = "300" height = "45">
</applet>
</html> 8
7.3 HTML tags and Java Applets
An appletviewer may be used instead of a WWW browser to test applets. For
example, the output of TrivialApplet on an appletviewer looks like:
HTML/Applet Interface
The HTML applet tag is similar to the HTML img tag, and has the form:
<applet code=AppletName.class width=w height=h>
[parameters]
</applet>
where the optional parameters are a list of parameter definitions of the form:
<param name=n value=v>
An example tag with parameter definitions is:
<applet code=AppletName.class width=300 height=200>
<param name=p1 value=34>

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
.

The sample program WelcomeApplet executing in the appletviewer and in Microsoft


Internet Explorer Web browser. To execute an applet in Internet Explorer, perform the
following steps:

1. Select Open... from the File menu.

2. In the dialog box that appears, click the Browse... button.

3. In the dialog box that appears, locate the directory containing the HTML document for
the applet you wish to execute.

4. Select the HTML document.

5. Click the Open button.

6.Click the OK button.

[Note: The steps for executing applets in other Web browsers are similar.]

11
// AdditionApplet.java
* .

// Adding two floating-point numbers.


import java.awt.Graphics; // program uses class Graphics
import javax.swing.JApplet; // program uses class JApplet
import javax.swing.JOptionPane; // program uses class JOptionPane

public class AdditionApplet extends JApplet {


private double sum; // sum of values entered by user
// initialize applet by obtaining values from user
public void init () {
String firstNumber; // first string entered by user
String secondNumber; // second string entered by user
double number1; // first number to add
double number2; // second number to add
// obtain first number from user
firstNumber = JOptionPane.showInputDialog( "Enter first floating-point value" );
// obtain second number from user
secondNumber = JOptionPane.showInputDialog( "Enter second floating-point value" );
// convert numbers from type String to type double
number1 = Double.parseDouble( firstNumber );
number2 = Double.parseDouble( secondNumber );
12
sum = number1 + number2; // add numbers
} // end method init
// draw results in a rectangle on applet's background
public void paint( Graphics g ) {
super.paint( g ); // call superclass version of method paint
// draw rectangle starting from (15, 10) that is 270 pixels wide and 20 pixels tall
g.drawRect( 15, 10, 270, 20 );
// draw results as a String at (25, 25)
g.drawString( "The sum is " + sum, 25, 25 );
} // end method paint
} // end class AdditionApplet

AdditionApplet.html loads class AdditionApplet


<html>
<applet code = "AdditionApplet.class" width = "300" height = "65">
</applet>
</html>

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
}
}

You might also like