Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Summary of applet knowledge points in java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "summary of applet knowledge points in java". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "summary of applet knowledge points in java".

Applet introduction

Applet can be translated into applets, Java Applet is written in Java language such small applications, they can be directly embedded in the web page, and can produce special effects. Web pages that contain Applet are called Java-powered pages, and can be called Java-supported pages.

When a user visits such a web page, the Applet is downloaded to the user's computer for execution, but only if the user is using a web browser that supports Java. Because Applet is executed on the user's computer, its execution speed is not limited by network bandwidth or Modem access speed. Users can better appreciate the multimedia effects produced by Applet on the web page.

In Java Applet, it can realize the functions of graphic drawing, font and color control, animation and sound insertion, human-computer interaction and network communication. Applet also provides a window environment development tool called Abstract window Toolkit (Abstract Window Toolkit, AWT). Using the GUI element of the user's computer, AWT can establish a standard graphical user interface, such as windows, buttons, scroll bars, and so on. At present, there are many Applet examples on the Internet to vividly demonstrate these functions, and readers can refer to the corresponding web pages to see their effects.

How Applet works.

The HTML file code of a web page containing Applet has a pair of tags in the middle, and when a web browser that supports Java encounters these tags, it will download the corresponding applet code and execute the Applet on the local computer.

Applet sample example

Java

Package com.boonya.applet;import java.applet.Applet;import java.applet.AppletContext;import java.applet.AudioClip;import java.awt.Dimension;import java.awt.Graphics;import java.awt.Image;import java.net.URL;import java.util.Locale;import javax.accessibility.AccessibleContext / * * @ packge com.boonya.applet.HelloWorldApplet * @ date 11:06:36 on August 20, 2019 * @ author pengjunlin * @ comment Java Mini Program: its function is to display images and play sounds Its life cycle init- > start- > paint- > stop- > destory * @ update * / @ SuppressWarnings ("serial") public class HelloWorldApplet extends Applet {@ Override public boolean isActive () {/ / TODO Auto-generated method stub return super.isActive () @ Override public URL getDocumentBase () {/ / TODO Auto-generated method stub return super.getDocumentBase ();} @ Override public URL getCodeBase () {/ / TODO Auto-generated method stub return super.getCodeBase () } @ Override public String getParameter (String name) {/ / TODO Auto-generated method stub return super.getParameter (name);} @ Override public AppletContext getAppletContext () {/ / TODO Auto-generated method stub return super.getAppletContext () } @ Override public void resize (int width, int height) {/ / TODO Auto-generated method stub super.resize (width, height);} @ Override public void resize (Dimension d) {/ / TODO Auto-generated method stub super.resize (d) } @ Override public boolean isValidateRoot () {/ / TODO Auto-generated method stub return super.isValidateRoot ();} @ Override public void showStatus (String msg) {/ / TODO Auto-generated method stub super.showStatus (msg) } @ Override public Image getImage (URL url) {/ / TODO Auto-generated method stub return super.getImage (url);} @ Override public Image getImage (URL url, String name) {/ / TODO Auto-generated method stub return super.getImage (url, name) } @ Override public AudioClip getAudioClip (URL url) {/ / TODO Auto-generated method stub return super.getAudioClip (url);} @ Override public AudioClip getAudioClip (URL url, String name) {/ / TODO Auto-generated method stub return super.getAudioClip (url, name) @ Override public String getAppletInfo () {/ / TODO Auto-generated method stub return super.getAppletInfo ();} @ Override public Locale getLocale () {/ / TODO Auto-generated method stub return super.getLocale () @ Override public String [] [] getParameterInfo () {/ / TODO Auto-generated method stub return super.getParameterInfo ();} @ Override public void play (URL url) {/ / TODO Auto-generated method stub super.play (url) } @ Override public void play (URL url, String name) {/ / TODO Auto-generated method stub super.play (url, name);} @ Override public void init () {/ / TODO Auto-generated method stub super.init () @ Override public void start () {/ / TODO Auto-generated method stub super.start ();} @ Override public void stop () {/ / TODO Auto-generated method stub super.stop () @ Override public void destroy () {/ / TODO Auto-generated method stub super.destroy ();} @ Override public AccessibleContext getAccessibleContext () {/ / TODO Auto-generated method stub return super.getAccessibleContext () } public void paint (Graphics g) {g.drawString ("Hello World", 25,50);}

Html

An Example Homepage Welcome to my homepage! This is an example homepage, you can see an applet in it .

Java Applet Foundation

Applet is a Java program. It generally runs in Web browsers that support Java. Because it has full Java API support, Applet is a full-featured Java application.

The following is an important difference between stand-alone Java applications and applet programs:

The Applet class in Java inherits the java.applet.Applet class.

The Applet class does not define main (), so an Applet program does not call the main () method.

Applet is designed to be embedded in a HTML page.

When the user browses the HTML page that contains Applet, the Applet code is downloaded to the user's machine.

JVM is required to view an Applet. JVM can be a plug-in for Web browsers or a separate runtime environment.

The JVM on the user's machine creates an instance of the Applet class and calls various methods in the Applet life cycle.

Applet has strict security rules enforced by Web browsers, and the security mechanism of Applet is called sandboxing security.

Other classes required by Applet can be downloaded as Java archive (JAR) files.

Life cycle of Applet

The four methods in the Applet class provide us with a framework on which you can develop Mini Program:

Init: the purpose of this method is to provide any initialization required for your Applet. This method is called after the param tag within the Applet tag is processed.

Start: after the browser calls the init method, this method is called automatically. This method is called whenever the user returns from another page to the page that contains Applet.

Stop: this method is automatically called when the user is removed from the page that contains Applet. Therefore, the method can be called repeatedly in the same Applet.

Destroy: this method is called only when the browser closes normally. Because Applet is only valid on HTML pages, you should not miss any resources after the user leaves the page that contains Applet.

Paint: this method is called immediately after the start () method, or when the Applet needs to be redrawn in the browser. The paint () method actually inherits from java.awt.

Applet class

Each Applet is a subclass of the java.applet.Applet class, and the underlying Applet class provides methods that can be called by the derived class to get browser context information and services.

These methods do the following:

Get the parameters of Applet

Get the network location of the HTML file containing Applet

Get the network location of the Applet class directory

Print the status information of the browser

Get a picture

Get an audio clip

Play an audio clip

Resize this Applet

In addition, the Applet class provides an interface for Viewer or browsers to obtain information about Applet and to control the execution of Applet.

Viewer may be:

Request information about Applet author, version, and copyright

Description of the parameters identified by the request Applet

Initialize Applet

Destroy Applet

Start Applet execution

End execution of Applet

The Applet class provides a default implementation of these methods, which can be overridden when needed.

The "Hello,World" applet is written according to the standard. The only method that is overridden is the paint method.

The call of Applet

Applet is a Java program. It generally runs in Web browsers that support Java. Because it has full Java API support, Applet is a full-featured Java application.

Tags are the basis for embedding Applet in HTML files. Here is an example of calling "Hello World" applet

HTML Code:

The Hello, World AppletIf your browser was Java-enabled, a "Hello, World" message would appear here.

Note: you can learn more about calling applet from HTML by referring to the HTML Applet tag.

The attribute of the tag specifies the Applet class to run. Width and height are used to specify the initial size of the Applet run panel. Applet must be closed with a tag.

If Applet accepts a parameter, then the value of the parameter needs to be added to the tag, which is between and. The browser ignores the text and other tags between the applet tags.

Browsers that do not support Java cannot execute and. Therefore, anything that appears between tags and has nothing to do with applet is visible in browsers that do not support Java.

The Viewer or browser looks for compiled Java code in the location of the document. To specify the path to the document, use the codebase attribute of the tag.

As follows:

If the Applet is in a package instead of the default package, the package must be specified in the code property, for example:

Get applet parameters

The following example shows how to use an Applet response to set the parameters specified in the file. The Applet shows a black chessboard pattern and a second color.

The second color and the size of each column are specified by the parameter Applet in the document.

CheckerApplet gets its parameters in the init () method. You can also get its parameters in the paint () method. However, it is convenient and efficient to get values at the beginning of Applet and save settings instead of getting values every time you refresh.

The Applet viewer or browser calls the init () method every time Applet runs. Immediately after loading the Applet, Viewer calls the init () method (Applet.init () does nothing) to override the default implementation of the method and add some custom initialization code.

The Applet.getParameter () method gets the parameter value by giving the parameter name. If the resulting value is a number or other non-character data, it must be parsed to a string type.

The following example is a modification of CheckerApplet.java:

CheckerApplet.java file code:

Import java.applet.*;import java.awt.*;public class CheckerApplet extends Applet {int squareSize = 50ramp / initialize default size public void init () {} private void parseSquareSize (String param) {} private Color parseColor (String param) {} public void paint (Graphics g) {}}

Here are the init () method of the CheckerApplet 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) {/ / keep the default}

The Applet calls parseSquareSize () to parse the squareSize parameter. ParseSquareSize () calls the library method Integer. ParseInt () this method parses a string to an integer, and Integer.parseInt () throws an exception when the argument is invalid.

Therefore, the parseSquareSize () method also catches exceptions and does not allow Applet to accept invalid input.

Applet calls the parseColor () method to resolve the color parameter to a Color value. The parseColor () method makes a series of string comparisons to match the value of the parameter with the name of the predefined color. You need to implement these methods to make Applet work.

Specify applet parameters

The following example is a HTML file with an embedded CheckerApplet class. The HTML file specifies two parameters to applet by using tags.

Checkerboard Applet

Note: parameter names are case-insensitive.

Convert the application to Applet

It is easy to convert a graphical Java application (that is, an application that uses AWT and a program launched using the java program launcher) into an applet embedded in a web page.

Here are a few steps to convert an application to Applet:

Write a HTML page with tags that can load applet code.

Write a subclass of the JApplet class and set the class to public. Otherwise, Applet cannot be loaded.

Eliminate the main () method of the application. Do not construct a frame window for your application, because your application will be displayed in the browser.

Move the initialization code in the constructor of the frame window in the application to the init () method of Applet, you do not have to display the construction Applet object, the browser will instantiate an object by calling the init () method.

Remove the call to the setSize () method. For Applet, the size has been set by the width and height parameters in the HTML file.

Remove the call to the setDefaultCloseOperation () method. Applet cannot be closed, it terminates with the exit of the browser.

If the application calls the setTitle () method, eliminate the call to that method. Applet cannot have a title block. (of course you can name the page itself through the title tag of html)

Do not call setVisible (true), Applet is automatically displayed.

Event handling

The Applet class inherits many event handling methods from the Container class. The Container class defines several methods, such as processKeyEvent () and processMouseEvent (), to handle special types of events, and a method called processEvent to capture all events.

In order to respond to an event, Applet must override the appropriate event handling method.

ExampleEventHandling.java file code:

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 applet");} 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:

Event Handling

At first, Applet displays "initializing the applet. Starting the applet." and then when you click on the rectangle, it displays "mouse clicked".

Show picture

Applet can display pictures in other formats such as GIF,JPEG,BMP. To display the picture in 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:

ImageDemo.java file code:

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 (); / / Displayin 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:

The ImageDemo applet plays audio

Applet can play audio by using the AudioClip interface in the java.applet package. The AudioClip interface defines three methods:

Public void play (): play the audio clip once from the beginning.

Public void loop (): loop audio clips

Public void stop (): stop playing audio clips

To get the AudioClip object, you must call the getAudioClip () method of the Applet class. This method returns the result immediately, regardless of whether the URL is pointing to a real audio file.

The audio file is not downloaded until it is about to be played.

The following example demonstrates all the steps of playing audio:

AudioDemo.java file code:

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 applet as follows:

The ImageDemo applet

You can use the test.wav on your computer to test the above example.

Thank you for your reading, the above is the content of "summary of applet knowledge points in java". After the study of this article, I believe you have a deeper understanding of the summary of applet knowledge points in java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report