Java programming-sun Xin Java no difficulty lesson11 "applet"

Source: Internet
Author: User
Tags gety
Java programming -- Sun Xin Java has no difficulty lesson11 Applet Highlights of this section:
1. Applet programming: describes in detail the lifecycle of the applet and the settings of the child.
2. the applet obtains information from the webpage, and communicates with the browser.
3. the applet updates the display principle, uses the applet to make the animation program, and optimizes the animation program.
Details:

1. Introduction to Applet
(1) What is an applet?
Applet, also known as a Java small application, is a Java class that can be embedded into an HTML page and downloaded and executed through a web browser.
The applet does not need the main () method and is called and executed by the embedded Java Virtual Machine in the Web browser.
(2) applet security restrictions
Because the applet is downloaded from a remote server and executed locally, security is especially important.
By limiting the running of the applet in the sandbox (the running environment of the applet), the applet is safe for the local system.
When the applet runs in the sandbox:
A. You cannot run any local executable program;
B. Apart from the server where the downloaded applet is stored, the applet cannot communicate with other hosts.
C. The local file system cannot be read/written.
(3) applet Lifecycle
Init (): This method is called when the browser loads the applet and initializes it.
Start (): called after the init () method. This method is also called when a user switches from another page to a page containing the applet.
Stop (): called when the user leaves the page containing the applet.
Destroy (): This method is called when the applet is no longer used or the browser exits.
2. Interaction between Applet and browser
(1) applet obtains webpage Information
Just as the application can obtain information through command line parameters, the applet can obtain information from the webpage by using the param tag.
(2) Communication between Applet and browser
Display information in the browser. Call the showstatus () method in the appletcontext interface.
Request the browser to display the specified webpage and call the showdocument () method in the appletcontext interface.
The simple applet test code is as follows:

Package imagetest; import Java. applet. applet; import Java. AWT. graphics; import Java. AWT. color; import Java. AWT. font; import Java. AWT. button; import Java. AWT. event. mouseadapter; import Java. AWT. event. mouseevent; import Java. AWT. event. actionlistener; import Java. AWT. event. actionevent; import java.net. URL; public class testapplet extends applet {string strfont; int xorigin, yorigin; Public void Init () {button BTN = new button ("Link "); // write the status bar getappletcontext (). showstatus ("Java Applet test, a simple demo"); add (BTN); // link the new file BTN. addactionlistener (New actionlistener () {public void actionreceivmed (actionevent e) {try {getappletcontext (). showdocument (new URL (getdocumentbase (), "test.html"), "_ blank");} catch (exception ex) {ex. printstacktrace () ;}}); // obtain the webpage font information strfont = getparameter ("font"); // capture the user's mouse action to draw a straight line addmouselistener (New mouseadapter () {public void mousepressed (mouseevent e) {xorigin = E. getx (); yorigin = E. gety ();} public void mousereleased (mouseevent e) {graphics G = getgraphics (); G. setcolor (color. red); G. drawline (xorigin, yorigin, E. getx (), E. gety () ;}}) ;}public void start () {system. out. println ("START");} public void stop () {system. out. println ("stop");} public void destroy () {system. out. println ("Destroy");} // drawing Operation Public void paint (Graphics g) {// font F = new font (" 文 ", Font. bold, 30); // construct the font F = new font (strfont, Font. bold, 30); G. setfont (f); G. setcolor (color. blue); G. drawstring ("Java Applet test",) ;}// applettest.html/* <APPLET code = "imagetest. testapplet. class "width = 600 Height = 400> <Param name =" font "value =" _ gb2312 "> */

Shows the running effect:

3. AWT plotting
(1) paint () method
Essentially, the applet is a graphical method. We should draw our display content in the graphic environment.
We can create a painting () method to draw on the panel of the applet. As long as the applet display needs to be refreshed, the paint () method will be called by the browser environment. For example, when the display size of the applet changes, or the browser window is minimized or required to be displayed as an icon, this call will occur.
We should write our own paint () method so that it can work normally at any time. Calls to the program are generated asynchronously and driven by the running environment of the applet rather than the program.
The paint () method has a parameter, which is an instance of the Java. AWT. graphics class. This parameter always establishes the graphic context of the panel of the applet. We can use this graphic context to draw or write text in the applet.
(2) AWT plotting update and Method
Update display is completed by an independent thread called an AWT thread. This thread can be used to handle two situations related to display updates.
First caseIs exposure, which appears when it is displayed for the first time, or when part of the display has been damaged and must be refreshed. The display corruption may occur at any time, so our program must be able to update the display at any time.
Case 2It is when the program re-draws a picture with new content. This type of re-painting may require that the original image be erased first.
AWT update method:
The paint (Graphics g) method is called when the component is displayed for the first time or when the damaged part needs to be repaired. Unless necessary, updates do not completely cover the entire graphic area, but are strictly restricted to the scope of destruction.
The repaint () method calls repaint () to notify the system: If you want to change the display, the system will call paint ().
The Update (Graphics g) method repaint () actually generates an AWT thread that calls another method Update. The update method usually clears the current display and calls the paint () method (). The Update () method can be modified. For example, you can directly call the paint () method to reduce the amount of flashes but not to clear the display ().
The code of the applet simple image display program is as follows:

Package imagetest; import Java. applet. applet; import Java. AWT. graphics; import Java. AWT. image; // simple image display public class showimage extends applet {private image [] IMGs; private int totalimage = 10; private int currentimage = 0; Public void Init () {IMGs = new image [totalimage]; // do not forget to allocate memory. // The Image array is constructed, but the image is not loaded for (INT I = 0; I <totalimage; ++ I) IMGs [I] = getimage (getdocumentbase (), "T" + (I + 1) + ". GIF ");} public void start () {currentimage = 0;} public void paint (Graphics g) {G. drawimage (IMGs [currentimage], 0, 0, this); // display the image to the applet panel currentimage = (++ currentimage) % totalimage; try {thread. sleep (500); // pause} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace ();} repaint (); // the next image is displayed after the next update.}/* // The following public void Update (Graphics g) method cannot be used for showimage) {paint (g);} */Private Static final long serialversionuid = 1l ;}

The code of the applet double buffer image display program is as follows:

Package imagetest; import Java. applet. applet; import Java. AWT. color; import Java. AWT. graphics; import Java. AWT. image; import Java. AWT. mediatracker; // double-buffered display image to reduce the blinking public class doublebufferimage extends applet {private image [] IMGs; private int totalimage = 10; private int currentimage = 0; private image imgbuf; private graphics gbuf; private mediatracker MT; // tracks the media status public void Init () {Mt = new mediatracker (this ); // imgbuf = createimage (600,400); gbuf = imgbuf. getgraphics (); gbuf. setcolor (color. white); gbuf. fillrect (0, 0, 600,400); IMGs = new image [totalimage]; // do not forget to allocate memory for (INT I = 0; I <totalimage; ++ I) {IMGs [I] = getimage (getdocumentbase (), "T" + (I + 1) + ". GIF "); Mt. addimage (IMGs [I], I);} Try {Mt. waitforid (0); // wait for the image to load} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace () ;}} public void start () {currentimage = 0; gbuf. drawimage (IMGs [currentimage], 0, 0, this); currentimage = 1;} public void paint (Graphics g) {// the current context graph G. drawimage (imgbuf, 0, 0, this); // gbuf for drawing outside the screen. fillrect (600,400,); // check whether the image is loaded. If it is loaded, it is waiting for loading if (MT. checkid (currentimage, true) {gbuf. drawimage (IMGs [currentimage], 0, 0, this); currentimage = (++ currentimage) % totalimage;} Try {thread. sleep (500); // pause} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace () ;} repaint () ;}// this method can be used to update (Graphics g) {paint (g );} private Static final long serialversionuid = 1l ;}

The program code of the applet multi-threaded image display is as follows:

Package imagetest; import Java. applet. applet; import Java. AWT. color; import Java. AWT. graphics; import Java. AWT. image; import Java. AWT. mediatracker; // multi-threaded dual-buffer display image public class multithreadimage extends applet implements runnable {Private Static final long serialversionuid = 1l; private Boolean bstop = false; private image [] IMGs; private int totalimage = 10; private int currentimage = 0; private image imgbuf; private gr Aphics gbuf; private mediatracker MT; Public void Init () {Mt = new mediatracker (this); // trace media status // map imgbuf = createimage (600,400) outside the screen ); gbuf = imgbuf. getgraphics (); gbuf. setcolor (color. white); gbuf. fillrect (0, 0, 600,400); IMGs = new image [totalimage]; // do not forget to allocate memory for (INT I = 0; I <totalimage; ++ I) {IMGs [I] = getimage (getdocumentbase (), "T" + (I + 1) + ". GIF "); Mt. addimage (IMGs [I], I);} Try {Mt. waitforid (0);} catch (interruptedexception E) {// todo auto-generated catch blocke. printstacktrace () ;}} public void start () {currentimage = 0; gbuf. drawimage (IMGs [currentimage], 0, 0, this); New thread (this ). start (); // start thread currentimage = 1;} public void paint (Graphics g) {// current context graph G. drawimage (imgbuf, this);} // because the drawing has been completed in the memory, you can use this method public void Update (Graphics g) {paint (g );} // implement the interface method public void run () {// pay attention to the processing skills of thread exit while (! Bstop) {// drawing gbuf outside the screen. fillrect (0, 0, 600,400); If (MT. checkid (currentimage, true) {gbuf. drawimage (IMGs [currentimage], 0, 0, this); currentimage = (++ currentimage) % totalimage;} Try {thread. sleep (500); // pause} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace () ;}repaint () ;}// stop the thread public void stop () {bstop = true ;}}

The running effect is shown in (because the picture is put here, there is no difference in itself, so only one image is put ):

The update method is called incorrectly in showimage, causing overlapping images, as shown in:


4. html tag and attributes of the Applet
The applet attribute used for positioning:
(1) width and height: Set the width and height of the applet in pixels.
(2) Align: an optional attribute that specifies the alignment mode of the applet.
Left: place the applet on the left side of the Web page. The text following the applet will be moved to the right side of the applet.
Right: place the applet on the right of the web page, and the text behind it will be moved to the left of the applet.
Bottom: Align the bottom of the applet with the bottom of the current text line.
Top: Align the top of the applet with the top of the current row.
Texttop: Align the top of the applet with the top of the text in the current line.
Middle: Align the middle Of the applet with the baseline of the current row.
Absmiddle: Align the middle Of the applet with the middle of the current row.
Baseline: Align the bottom of the applet with the baseline of the current row.
Absbottom: Align the bottom of the applet with the bottom of the current row.
(3) vspace and hspace: an optional attribute that specifies the number of pixels on/Under the applet (vspace) and the number of pixels on both sides of the applet (heatace ).
The applet attributes used for encoding:
(1) code: Specifies the name of the Applet Class file. This name is relative to codebase, and is relative to the current page.
(2) codebase: an optional attribute that tells the browser to find a class file.
(3) archive: an optional attribute that lists Java archive files, files containing class files, or other resources required by the applet.
(4) object: Another method used to specify the Applet Class file.
(5) name: an optional attribute. The page script writer wants to assign the applet name attribute. In this way, when writing a script, you can use the name specified for this attribute to represent this applet.
Supplement:
(1) The packaging of Applet programs and resource files is as follows:

F: \ Java \ javalesson \ lesson11> jar-CVF imagetest. Jar imagetest T *. gif *. html

(2) The audio test code is as follows:

Package audiotest; import Java. applet. applet; import Java. applet. audioclip; public class playsound extends applet {Private Static final long serialversionuid = 1l; private audioclip AC; Public void Init () {// play (getdocumentbase (), "1.au "); // continuous playback AC = getaudioclip (getdocumentbase (), "1.au"); AC. loop ();} public void stop () {AC. stop ();}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.