Transcript Note-28-11

Java applet basics, loading &
displaying images
After this section, you should be able to :
–
–
–
–
–
–
–
–
–
Use the applet tag and applet parameters
Describe what a Java package is
Import a package containing additional Java types
Describe what the paint method do
Understand the function of Graphics class
Declare a reference to an image object
Load an image in an applet
Code a paint method
Draw an image into a Graphics object
The Applet tag and Applet
Parameters
• The <APPLET> tag is used to add a Java applet
to a Web page
<APPLET CODE="HelloWorldApplet.class" HEIGHT=50
WIDTH=150> </APPLET>
• Applets use applet parameters to customize
their behaviour. Applet parameters are specified
by using <PARAM> tags, which can only occur
between an <APPLET> tag and the closing
</APPLET>. The PARAM tag has required
modifiers named NAME and VALUE, and it
takes the form
<PARAM NAME="param-name" VALUE="param-value">
An example of an Applet tag with
PARAMs
<APPLET code="ShowMessage.class" WIDTH=200 HEIGHT=50> <PARAM
NAME="message" VALUE="Goodbye World!">
<PARAM NAME="font" VALUE="Serif">
<PARAM NAME="size" VALUE="36">
<p align=center>Sorry, but your browser doesn't support Java!</p>
</APPLET>
String display; // Instance variable: message to be displayed.
String fontName; // Instance variable: font to use for display.
public void init() {
String value;
value = getParameter("message"); // Get message PARAM, if any.
if (value == null) display = "Hello World!"; // default value
else display = value; // Value from PARAM tag.
value = getParameter("font");
if (value == null) fontName = "SansSerif"
else fontName = value;
……………………}
Packages
A package is a named group of classes for a
common domain: java.lang, java.awt, java.util,
java.io. Packages can be imported by other
source files making the names available:
import java.awt.*; // All classes
import java.awt.Image; // One class
Explicit type name: java.awt.Image i1;
Implicit type name: import java.awt.*; Image i2;
The java.lang package is automatically imported
by the compiler.
The java.lang package
The java.lang package contains more than 20 classes,
of which the most useful are System, String, and Math. It
also contains the Thread class, the Runnable interface,
and the various wrapping classes (such as Integer).
1. java.lang.System class provides the standard streams in, out,
and err as public class variables.
2. java.lang.String class contains methods that provide functions
similar to C's strxxx functions, including charAt, compareTo,
concat, endsWith equals, length, replace, startsWith,
subString, toLowerCase, and trim.
3. java.lang.Math class contains a number of mathematical
methods such as abs, sin, cos, atan, max, min, log, random,
and sqrt. It also contains E and PI as class constants (static
final).
Applet class
• The Applet class, defined in the package java.applet, is
really only useful as a basis for making subclasses.
• An object of type Applet has certain basic behaviours,
but doesn't actually do anything useful. It's just a blank
area on the screen that doesn't respond to any events.
To create a useful applet, a programmer must define a
subclass that extends the Applet class.
• There are several methods in the Applet class that are
defined to do nothing at all. The programmer must
override at least some of these methods and give them
something to do.
Paint method
• One of the methods that is defined in the Applet class to do nothing
is the paint() method.
• The paint() method is called by the system when the applet needs to
be drawn. In a subclass of Applet, the paint() method can be
redefined to draw various graphical elements such as rectangles,
lines, and text on the applet. The definition of this method must have
the form:
public void paint(Graphics g) {
// draw some stuff
}
The parameter g, of type Graphics, is provided by the system when
it calls the paint() method. In Java, all drawing of any kind is done
using methods provided by a Graphics object. There are many such
methods and I will introduce them to you soon
Something paint cannot do
• The paint() method of an applet does not
draw GUI components such as buttons
and text input boxes that the applet might
contain. Such GUI components are
objects in their own right, defined by other
classes. All component objects, not just
applets, have paint() methods. Each
component is responsible for drawing
itself, in its own paint() method.
Graphics class
• A Graphics object is usually only obtained as an
argument to update and paint methods:
public void update(Graphics g) {...}
public void paint(Graphics g) {...}
• The Graphics class provides a set of drawing tools that
include methods to draw:
•
•
•
•
•
•
•
rectangles (drawRect, fillRect)
ovals (drawOval, fillOval)
arcs (drawArc, fillArc)
polygons (drawPolygon, fillPolygon)
rounded rectangles (drawRoundRect, fillRoundRect)
strings (drawString)
images (drawImage)
For example:
g.drawImage(i, 0, 0, this);
“Hello World” applet example
import java.awt.*;
import java.applet.*;
public class HelloWorldApplet extends Applet {
// An applet that simply displays the string Hello World!
public void paint(Graphics g) {
g.drawString("Hello World!", 10, 30);
}
} // end of class HelloWorldApplet
Another “Hello World” applet
example
// An applet that says "Hello World" in a big bold font,
// with a button to change the color of the message.
import java.awt.*; // Defines basic classes for GUI programming.
import java.awt.event.*; // Defines classes for working with events.
import java.applet.*; // Defines the applet class.
public class ColoredHelloWorldApplet extends Applet
implements ActionListener {
// Defines a subclass of Applet. The "implements ActionListener"
// part says that objects of type ColoredHelloApplet are
// capable of listening for ActionEvents. This is necessary
// if the applet is to respond to events from the button.
int colorNum; // Keeps track of which color is displayed;
// 1 for red, 2 for blue, 3 for green.
Font textFont; // The font in which the message is displayed.
// A font object represent a certain size and
// style of text drawn on the screen.
public void init() {
// This routine is called by the system to initialize
// the applet. It sets up the font and initial colors
// the applet. It adds a button to the applet for
// changing the message color.
setBackground(Color.lightGray);
// The applet is filled with the background color before
// the paint method is called. The button and the message
// in this applet will appear on a light gray background.
colorNum = 1; // The color of the message is set to red.
textFont = new Font("Serif",Font.BOLD,24);
// Create a font object representing a big, bold font.
Button bttn = new Button("Change Color");
// Create a new button. "ChangeColor" is the text
// displayed on the button.
bttn.addActionListener(this);
// Set up bttn to send an "action event" to this applet
// when the user clicks the button. The parameter, this,
// is a name for the applet object that we are creating. add(bttn);
// Add the button to the applet, so that it
// will appear on the screen.
} // end init()
public void paint(Graphics g) {
// This routine is called by the system whenever the content
// of the applet needs to be drawn or redrawn. It displays
// the message "Hello World" in the proper color and font.
switch (colorNum) { // Set the color.
case 1: g.setColor(Color.red); break;
case 2: g.setColor(Color.blue); break;
case 3: g.setColor(Color.green); break; }
g.setFont(textFont); // Set the font.
g.drawString("Hello World!", 20,70);
// Draw the message.
} // end paint()
public void actionPerformed(ActionEvent evt) {
// This routine is called by the system when the user clicks
// on the button. The response is to change the colorNum
// which determines the color of the message, and to call
// repaint() to see that the applet is redrawn with the
// new color.
if (colorNum == 1) // Change colorNum.
colorNum = 2;
else if (colorNum == 2)
colorNum = 3;
else colorNum = 1;
repaint(); // Tell system that this applet needs to be redrawn
} // end init()
} // end class ColoredHelloWorldApplet
Loading and drawing images
The typical way to load images in Applets is via the getImage()
method.
Image getImage(URL) // Absolute URL
Image getImage(URL, String) // Relative URL
For example:
Image img = getImage(getDocumentBase(), "x.gif");
This example returns a reference to an image object that is being
asynchronously loaded. The getDocumentBase() method returns the
address of the current Web site where the applet is being executed.
The x.gif is the actual image being loaded
After the image is loaded, you would typically render it to the screen
in the Applet's paint method using the Graphics method. For
example:
g.drawImage(img, 0, 0, this); // img is the image that is drawn on the
// screen in the 0, 0 position.
Simple applet that loads and draws
Image
<applet code=ImgLoad width=300 height=200>
</applet>
import java.awt.*;
public class ImgLoad extends java.applet.Applet {
Image i;
public void init() {
System.out.println("In init");
i = getImage(getDocumentBase(), "Test.gif");
}
public void paint(Graphics g) {
System.out.println("In paint");
int x = (int)(Math.random() * size().width);
int y = (int)(Math.random() * size().height);
g.drawImage(i, x, y, this);
}
}