📄 clock.java
字号:
//Listing 6-6 -- Clock.java
import java.applet.*;
import java.awt.*;
public class Clock extends Applet implements Runnable {
private Thread th_thread; // Thread for the runnable interface
private Image im_images[]; // Image array for animation
private int i_currImage; // Current Image to display
private int i_imageWidth = 0; //Width of Image
private int i_imageHeight = 0; // Height of Image
// Boolean set to true when all the images have loaded
private boolean b_allLoaded = false; // Boolean for all loaded
private final int i_numImages = 12; // Number of Images
public void init() {
resize(320, 240);
//Run thread, which calls the run method
th_thread = new Thread(this);
th_thread.start();
}
public void run() { // Called for Thread support.
i_currImage = 0;
String imageName;
// Array to store images
im_images = new Image[i_numImages];
Graphics g = getGraphics();
showStatus("Loading images...");
for (int i = 1; i <= i_numImages; i++) {
String picNum = Integer.toString(i);
if (picNum.length() < 2) {
picNum = "0" + picNum;
}
imageName = "CLOCK" + picNum + ".gif"; // Image file
im_images[i-1] = getImage(
getDocumentBase(), imageName);
// Get width and height of one image. Assume
// all images are same width and height
if (i_imageWidth == 0) {
try {
while ((i_imageWidth =
im_images[i-1].getWidth(null)) < 0)
Thread.sleep(1);
while ((i_imageHeight =
im_images[i-1].getHeight(null)) < 0)
Thread.sleep(1);
}
catch (InterruptedException e) { }
}
// Force image to fully load
g.drawImage(im_images[i-1], -1000, -1000, this);
}
// Wait until images are fully loaded
while (!b_allLoaded) {
try { Thread.sleep(10); }
catch (InterruptedException e) { }
}
showStatus("Done loading images.");
while (true) {
try { // Draw next image in animation
displayImage(g);
i_currImage++;
if (i_currImage == i_numImages)
i_currImage = 0;
Thread.sleep(500);
}
catch (InterruptedException e) {stop();}
}
}
private void displayImage(Graphics g) {
if (!b_allLoaded)
return;
g.drawImage(im_images[i_currImage],
(getSize().width - i_imageWidth) / 2,
(getSize().height - i_imageHeight) / 2, null);
}
public void paint(Graphics g) {
if (b_allLoaded) {
Rectangle r = g.getClipBounds();
g.clearRect(r.x, r.y, r.width, r.height);
displayImage(g);
}
}
public boolean imageUpdate(Image img, int flags,
int x, int y, int w, int h) {
// Nothing to do if images are all loaded
if (b_allLoaded)
return false;
// Want all bits to be available before painting
if ((flags & ALLBITS) == 0)
return true;
// All bits are available, so increment loaded count
// of fully loaded images, starting animation if all
// images are loaded
if (++i_currImage == i_numImages) {
i_currImage = 0;
b_allLoaded = true;
}
return false;
}
public void stop() {
if (th_thread != null) {
th_thread.stop();
th_thread = null;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -