Java Applet Animation Design

Source: Internet
Author: User
Tags count join thread

Applets are small programs that run in a browser, and Java is also popular in the world from applets. By writing this applet, we can learn the following knowledge:

1. Applet and the main interface in JApplet

2. Image loading and Mediatracker use

3. Use of threads and direct communication with multiple threads

4. Use of the Thread.Join () method

5. Use of volatile keywords

First look at the running effect: click to run

The main part of the animation is an applet that reads a set of picture files from the codebase, and then rotates the display one at a 1-second intervals. The code is as follows:

import javax.swing.JApplet;
import java.awt.Graphics;
import java.awt.Image;
Import Java.awt.MediaTracker;  
public class Animate extends JApplet
{
//Picture quantity
private static final int num_of_pic = 4;
int count;
Image pics[];
TimerThread Timer;   
public void init ()
{
count = 1;
pics = new Image[num_of_pic];
Mediatracker tracker = new Mediatracker (this);
for (int i = 0; i<num_of_pic; i++)
{
//to place the picture in the table of 0,1,..., num_of_pic-1, in the TOC, in the format. jpg
Pics[i] = GetImage (GetCodeBase (), New Integer (i). toString () + ". jpg");
Tracker.addimage (Pics[i], 0);  
}
Tracker.checkall (true);
  
public void Start ()
{
Timer = new TimerThread (this, 1000);
Timer.start ();   
}
public void Stop ()
{
Timer.shouldrun = false;
    Try
{
Timer.join ();
  Wait for the timer thread to exit
}
catch (Interruptedexception e) {};

public void Paint (Graphics g)
{
G.drawimage (pics[count++], 0, 0, null);
if (count = = num_of_pic) Count = 0;
}
}

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.