0% found this document useful (0 votes)
44 views8 pages

Programming Java: Applets

This document provides an overview of Java applets, including: - Applets allow programs to run in web browsers after being downloaded from web pages. They have security and safety issues. - The first example applet draws a string to the screen. Applets extend the Applet class and use Graphics to draw. - Applets have a lifecycle of init(), start(), stop(), destroy() methods. - The Graphics class provides methods for drawing shapes, text, and images. Colors can be set using the Color class. - Additional examples demonstrate getting applet dimensions, using fonts, and drawing within the applet space.

Uploaded by

April Joan Calla
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views8 pages

Programming Java: Applets

This document provides an overview of Java applets, including: - Applets allow programs to run in web browsers after being downloaded from web pages. They have security and safety issues. - The first example applet draws a string to the screen. Applets extend the Applet class and use Graphics to draw. - Applets have a lifecycle of init(), start(), stop(), destroy() methods. - The Graphics class provides methods for drawing shapes, text, and images. Colors can be set using the Color class. - Additional examples demonstrate getting applet dimensions, using fonts, and drawing within the applet space.

Uploaded by

April Joan Calla
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Programming Java

Applets

Incheon Paik

1 Applets
Java

Contents
„ Overview of Applets
„ First Java Applet
„ The Life Cycle of an Applet
„ The Graphics Class
„ Using Colors
„ Displaying Text
„ Using Applet Dimensions
„ Using Applets in a Web Page
„ The Applet Class
„ The AppletContext Class
„ Using Images
„ Using Threads
„ Double Buffering

2 Applets
Java
An Overview of Applets
Applets

‰ Applet : A program that can be referenced by


HTML source code of a Web page.
‰ Can be run on Web browser after having been
downloaded.
‰ May be dangerous
‰ Security Problem

3 Applets
Java

First Java Applet


import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="FirstApplet" width=200 height=200>
</applet>
*/

public class FirstApplet extends Applet {


public void paint(Graphics g) {
g.drawString("This is my first applet!", 20, 100);
}
}

‰ Extends Applet
‰ Graphics by Abstract Window Toolkit (AWT)
‰ Run: after compile,
appletviewer FirstApplet.html
or
appletviewer FirstApplet.java

4 Applets
Java
The Life Cycle of an Applet
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="AppletLifecycle" width=300
height=50>
</applet>
*/

public class AppletLifecycle extends Applet {


String str = "";

public void init() {


str += "init; ";
} ‰ init() : called only when the applet begins
public void start() { execution.
str += "start; ";
} ‰ start() : executed after init() method. Called
by the applet viewer or Web browser.
public void stop() {
str += "stop; "; ‰ stop() : when applet viewer is minimized.
}
‰ destroy() : called by the applet viewer or
public void destroy() { Web browser before the applet is terminated.
System.out.println("destroy");
}

public void paint(Graphics g) {


g.drawString(str, 10, 25);
}
}
5 Applets
Java

The Graphics Class


Methods of Graphics Class import java.applet.Applet;
import java.awt.Graphics;
abstract void drawArc(int x, int y, int w, int h, int degreesO,
int degrees1) /*
<applet code="DrawArc" width=200 height=200>
abstract boolean drawImage(Image img, int x, int y, Image </applet>
Observer io)
*/
abstract void drawLine(int x0, int y0, int x, int y1)
abstract void drawOval(int x, int y, int w, int h) pulic class DrawArc extends Applet {
abstract void drawPolygon(int x[], int u[], int n)
public void paint(Graphics g) {
abstract void drawPolyline(int x[], int y[], int n) g.drawArc(20, 20, 160, 160, 0, 135);
void drawRect(int x, int y, int w, int h) }
abstract void drawString(String str, int x, int y) }
abstract void fillArc(int x, int y, int w, int h, int degree0, int
degree1)
abstract void fillOval(int x ,int y, int w, int h)
abstract void fillPolygon(int x[], int y[], int n)
void fillRect(int x, int y, int w, int h)
abstract Color getColor()
abstract Font getFont()
abstract FontMetrics getFontMetrics()
abstract void setColor(Color c)
abstract void setFont(Font f)

http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Graphics.html

6 Applets
Java
Using Colors
import java.applet.Applet;
Color Constructors import java.awt.Color;
Color(int red, int green, int blue) import java.awt.Graphics;
/*
Color(int rgb) <applet code="BlueString" width=300 height=100>
Color(float r, float g, float b) </applet>
*/

public class BlueString extends Applet {


Method of Graphics Class
public void paint(Graphics g) {
static int HSBtoRGB(float h, float s, float b) g.setColor(Color.blue);
static float[] RGBtoHSB(int r, int g, int b, float hsb[]) g.drawString("Blue String", 100, 50);
}
Color brighter() }
Color darker()
static Color decode(String str) throws NumberFormatExcepti
on
boolean equals(Object obj)
int getBlue()
int getGreen()
int getRGB()
int getRed()

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Color.html

7 Applets
Java

Displaying Text
import java.applet.Applet;
Font Constructor import java.awt.*;
/*
Font(String name, int style, int ps) <applet code="FontDemo" width=200 height=200>
</applet>
*/

public class FontDemo extends Applet {


setFont() Method
abstract void setFont(Font font) public void paint(Graphics g) {

// Draw baseline
int baseline = 100;
g.setColor(Color.lightGray);
FontMetrics Constructor g.drawLine(0, baseline, 200, baseline);

FontMetrics(Font font) // Draw String


g.setFont(new Font("Serif", Font.BOLD, 36));
g.setColor(Color.black);
g.drawString("Wxyz", 5, baseline);
}
}
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Font.html

8 Applets
Java
Using Applet Dimensions
import java.applet.*;
getSize() Method import java.awt.*;
/*
Dimension getSize() <applet code="Circle" width=200 height=200>
</applet>
*/

public class Circle extends Applet {


Dimension Constructors
Dimension() public void paint(Graphics g) {
Dimension d = getSize();
Dimension(Dimension d) int xc = d.width / 2;
Dimension(int w, int h) int yc = d.height / 2;
int radius = (int)((d.width < d.height) ?
0.4 * d.width : 0.4 * d.height);
g.drawOval(xc - radius, yc - radius, 2 * radius, 2 *
radius);
}
}

http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Dimension.html

9 Applets
Java

Using Applets in a Web Page


Applet HTML Tag import java.applet.*;
import java.awt.*;
<applet /*
<applet code="BackgroundForeground" width=200
[codebase=url] height=200>
[alt=text] </applet>
[name=appName] */
width=wpixels
public class BackgroundForeground extends Applet {
height=hpixels
[align=alignment] public void paint(Graphics g) {
setBackground(Color.yellow);
[vspace=vspixels]
setForeground(Color.blue);
[hspace=hspixels] g.drawLine(0, 0, 200, 200);
> g.fillRect(100, 40, 50, 50);
[<param name=pname1 value=value1>] }
}
[<param name=pname2 value=value2>]
……….
[<param name=pnameN value=valueN>]
</applet>

10 Applets
Java
The Applet Class
import java.applet.*;
import java.awt.*;
java.lang.Object /*
<applet code="AppletParameters" width=300
height=300>
<param name="background" value="0xffffff">
java.awt.Component <param name="foreground" value="0x000000">
<param name="message" value="Testing Applet
Parameters">
</applet>
*/
java.awt.Container
public class AppletParameters extends Applet {

public void paint(Graphics g) {


java.awt.Panel String background = getParameter("background");
String foreground = getParameter("foreground");
String message = getParameter("message");
setBackground(Color.decode(background));
setForeground(Color.decode(foreground));
java.applet.Applet Font font = getFont();
FontMetrics fm = getFontMetrics(font);
Dimension d = getSize();
int x = (d.width - fm.stringWidth(message)) / 2;
int y = d.height / 2;
Applet and its superclasses g.drawString(message, x, y);
}
}

11 Applets
Java

The AppletContext Interface


import java.applet.*;
import java.awt.*;
import java.net.*;
AppletContext Interface /*
Applet getApplet(String appName) <applet code="ShowDocument" width=200
height=50>
Enumeration getApplets() </applet>
AudioClip getAudioClip(URL url) */
Image getImage(URL url)
public class ShowDocument extends Applet {
void showDocument(URL url)
void showDocument(URL url, String target) public void init() {
void showStatus(String str) AppletContext ac = getAppletContext();
try {
URL url = new URL("http://www.osborne.com");
ac.showDocument(url, "frame2");
}
catch(Exception e) {
showStatus("Exception: " + e);
}
}

public void paint(Graphics g) {


g.drawString("ShowDocument Applet", 10, 25);
}
}

12 Applets
Java
Using Images
import java.applet.*;
import java.awt.*;
getImage() Methods /*
<applet code="DrawImage" width=280 height=280>
Image getImage(URL url) <param name="file" value="kids2.jpg">
Image getImage(URL base, String fileName) </applet>
*/

public class DrawImage extends Applet {


Image image;
drawImage() Methods
public void init() {
abstract boolean drawImage(Image img, int x, int y, image = getImage(getDocumentBase(),
ImageObserver io) getParameter("file"));
}

public void paint(Graphics g) {


g.drawImage(image, 0, 0, this);
}
}

13 Applets
Java

Using Threads
public void run() {
try {
update() and repaint() Methods while(true) {
// Request a repaint
repaint() : request an update of the applet repaint();
display //Sleep before displaying next count
update() : clears the applet display with the Thread.sleep(1000);
background color and then invokes the paint() //Increment counter
method ++counter;
}
}
catch(Exception e) { }
public class Counter extends Applet }
implements Runnable {
int counter; public void paint(Graphics g) {
Thread t;
// Set Font
public void init() { g.setFont(new Font("Serif", Font.BOLD, 36));

// Initialize counter // Get font metrics


counter = 0; FontMetrics fm = g.getFontMetrics();

// Start thread // Display counter


t = new Thread(this); String str = "" + counter;
t.start(); Dimension d = getSize();
} int x = d.width / 2 - fm.stringWidth(str) / 2;
g.drawString(str, x, d.height / 2);
}
}
14 Applets
Java
Double Buffering (No Double Buffering)

Double Buffering can be used to avoid display “flicker” in applets.

import java.applet.*; // Request a repaint


import java.awt.*; repaint();
/*
<applet code="NoDoubleBuffer" width=300 //Sleep before update
height=100> Thread.sleep(100);
</applet> }
*/ }
catch(Exception e) {
public class NoDoubleBuffer extends Applet }
implements Runnable { }
int x = 0;
Thread t; public void paint(Graphics g) {

public void init() { // Draw filled circle


Dimension d = getSize();
// Start thread g.fillOval(x, d.height / 4, 50, 50);
t = new Thread(this);
t.start(); // Increment x
} x += 5;
if (x + 50 > d.width)
public void run() { x = 0;
try { }
while(true) { }

15 Applets
Java

Double Buffering (With Double Buffering)


import java.applet.*; // Sleep before update
import java.awt.*; Thread.sleep(100);
/* }
<applet code="DoubleBuffer" width=300 height=100> }
</applet> catch(Exception e) {
*/ }
}
public class DoubleBuffer extends Applet
implements Runnable { public void update(Graphics g) {
int x = 0; paint(g);
Thread t; }
Image buffer;
Graphics bufferg; public void paint(Graphics g) {
public void init() { //Get graphics object for buffer
if (bufferg == null)
// Start thread bufferg = buffer.getGraphics();
t = new Thread(this);
t.start(); //Draw to buffer
Dimension d = getSize();
// Create buffer bufferg.setColor(Color.white);
Dimension d = getSize(); bufferg.fillRect(0, 0, d.width, d.height);
buffer = createImage(d.width, d.height); bufferg.setColor(Color.black);
} bufferg.fillOval(x, d.height / 4, 50, 50);
public void run() { //Update screen
try { g.drawImage(buffer, 0, 0, this);
while(true) {
//Increment x
//Request a repaint x += 5;
repaint(); if (x + 50 > d.width)
x = 0;
}
}

16 Applets
Java

You might also like