May 10, 2021 Java
Applet is a Java program. I t typically runs in Java-supported Web browsers. Because it has full Java API support, applet is a full-featured Java application.
Here's an important difference between a stand-alone Java application and an applet:
The four methods in the Applet class give you a framework on which you can then develop small programs:
Here's a simple applet program HelloWorldApplet .java:
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}
Theseimport statements import the following classes into our applet class:
java.applet.Applet.
java.awt.Graphics.
Without theseimport statements, the Java compiler would not have recognized the Applet and Graphics classes.
Each applet is a sub-class of the java.applet.Applet class, and the underlying applet class provides methods for deriving class calls to get information and services in the browser context.
These methods do the following:
In addition, the Applet class provides an interface for Viewer or browser to obtain information about the applet and to control the execution of the applet.
The Viewer might be:
The Applet class provides a default implementation of these methods, which can be override when needed.
Hello, World applet is written by standard. The only way to be rewritten is the paint method.
Applet is a Java program. I t typically runs in Java-supported Web browsers. B ecause it has full Java API support, applet is a full-featured Java application.
The label is the basis for embedding the applet in the HTML file. H ere's an example of calling Hello World applet;
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Note: You can learn more about how to call an applet from HTML by referring to the HTML Applet tag.
The properties of the label specify the applet class to run. W idth and height are used to specify the initial size of the applet run panel. Applet must be turned off using the hashtag.
If the applet accepts the argument, the value of the argument is required The label is added, and the label is located between the .lt;applet> and the .lt;/applet> The browser ignores text and other labels between the applet tags.
Browsers that do not support Java cannot perform . applet . . and . Therefore, anything that appears between labels and has nothing to do with the applet is visible in the browser of the unsupported Java.
The Viewer or browser looks for compiled Java code at the location of the document, and to specify the path to the document, you need to specify it using the codebase property of the label.
Here's what it looks like:
<applet codebase="http://amrood.com/applets" code="HelloWorldApplet.class" width="320" height="120">
If the applet is in a package instead of the default package, the package must be specified in the code property, for example:
<applet code="mypackage.subpackage.TestApplet.class" width="320" height="120">
The following example shows how to use an applet response to set the parameters specified in the file. The applet shows a black board pattern and a second color.
The second color and the size of each column are specified by the parameters of the applet in the document.
CheckerApplet gets its parameters in the init() method. Y ou can also get its parameters in the pass() method. H owever, it's convenient and efficient to get values at the beginning of the applet and save the settings, rather than getting values every time you refresh them.
The applet viewer or browser calls the init() method every time the applet is running. I mmediately after loading the applet, viewer calls the init(Applet.init() method (Applet.init() does nothing), rewrites the default implementation of the method, and adds some custom initialization code.
The Applet.getParameter() method obtains the parameter value by giving the parameter name. I f the resulting value is a number or other non-character data, it must be resolved to a string type.
The following example is a summary .java CheckerApplet:
import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
int squareSize = 50;// 初始化默认大小
public void init () {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
Here's the init() method of the Checker Applet class and the private parseSquareSize() method:
public void init ()
{
String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);
String colorParam = getParameter ("color");
Color fg = parseColor (colorParam);
setBackground (Color.black);
setForeground (fg);
}
private void parseSquareSize (String param)
{
if (param == null) return;
try {
squareSize = Integer.parseInt (param);
}
catch (Exception e) {
// 保留默认值
}
}
The applet calls parseSquareSize() to parseSize parameters. P arseSquareSize() calls the library method Integer. p arseInt(), the method resolves a string to an integer, and When the argument is invalid, Integer.parseInt() throws an exception.
Therefore, the parseSquareSize() method also catches exceptions and does not allow the applet to accept invalid input.
Applet calls the parseColor() method to resolve the color parameters to a Color value. T he parseColor() method does a series of string comparisons to match the value of the argument and the name of the predefined color. Y ou need to implement these methods to make the applet work.
The following example is an HTML file embedded in the Checker Applet class. HTML files are used by using The label's method specifies two parameters for the applet.
<html>
<title>Checkerboard Applet</title>
<hr>
<applet code="CheckerApplet.class" width="480" height="320">
<param name="color" value="blue">
<param name="squaresize" value="30">
</applet>
<hr>
</html>
Note: The case of the parameter name is insensitive.
Converting graphical Java applications (i.e., applications that use AWT and programs started with java program launchers) into applets embedded in web pages is simple.
Here are a few steps to converting an application into an applet:
The Applet class inherits many event handling methods from the Container class. T he Container class defines several methods, such as processKeyEvent() and processMouseEvent(), which handle special types of events, and a method for capturing all events called processEvent.
In order to respond to an event, applet must override the appropriate event handling method.
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
public class ExampleEventHandling extends Applet
implements MouseListener {
StringBuffer strBuffer;
public void init() {
addMouseListener(this);
strBuffer = new StringBuffer();
addItem("initializing the apple ");
}
public void start() {
addItem("starting the applet ");
}
public void stop() {
addItem("stopping the applet ");
}
public void destroy() {
addItem("unloading the applet");
}
void addItem(String word) {
System.out.println(word);
strBuffer.append(word);
repaint();
}
public void paint(Graphics g) {
//Draw a Rectangle around the applet's display area.
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);
//display the string inside the rectangle.
g.drawString(strBuffer.toString(), 10, 20);
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
addItem("mouse clicked! ");
}
}
Call the applet as follows:
<html>
<title>Event Handling</title>
<hr>
<applet code="ExampleEventHandling.class" width="300" height="300">
</applet>
<hr>
</html>
At the beginning of the run, applet displays "initializing the applet. S tarting the applet." And then as soon as you click on the rectangular box, you'll see "mouse clicked."
Applet can display GIFs, JPEG, BMP and other formats of pictures. I n order to display pictures in the applet, you need to use the drawImage() method of the java.awt.Graphics class.
The following example demonstrates all the steps to display a picture:
import java.applet.*;
import java.awt.*;
import java.net.*;
public class ImageDemo extends Applet
{
private Image image;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{
imageURL = "java.jpg";
}
try
{
URL url = new URL(this.getDocumentBase(), imageURL);
image = context.getImage(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
// Display in browser status bar
context.showStatus("Could not load image!");
}
}
public void paint(Graphics g)
{
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.javalicense.com", 35, 100);
}
}
Call the applet as follows:
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="300" height="200">
<param name="image" value="java.jpg">
</applet>
<hr>
</html>
Applet can play audio by using the AudioClip interface in the java.applet package. The AudioClip interface defines three methods:
In order to get the AutoClip object, you must call the getAudioClip() method of the Applet class. W hether or not the URL points to a real audio file, the method returns the results immediately.
The audio file will not be downloaded until you want to play it.
The following example demonstrates all the steps to play audio:
import java.applet.*;
import java.awt.*;
import java.net.*;
public class AudioDemo extends Applet
{
private AudioClip clip;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String audioURL = this.getParameter("audio");
if(audioURL == null)
{
audioURL = "default.au";
}
try
{
URL url = new URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
context.showStatus("Could not load audio file!");
}
}
public void start()
{
if(clip != null)
{
clip.loop();
}
}
public void stop()
{
if(clip != null)
{
clip.stop();
}
}
}
Call the applet as follows:
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="0" height="0">
<param name="audio" value="test.wav">
</applet>
<hr>
You can test the instance above .wav test the test on your computer.