animateframe.java

来自「里面包含了多个java的编程示例!而且举出初学者常常遇到的错误!」· Java 代码 · 共 71 行

JAVA
71
字号
import java.awt.*;
import javax.swing.*;

public class AnimateFrame extends JFrame {
    public AnimateFrame() {
        super("Lighthouse");
        setSize(215, 298);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        AnimatePanel canvas = new AnimatePanel();
        add(canvas);
        setVisible(true);
    }

    public static void main(String[] arguments) {
        AnimateFrame af = new AnimateFrame();
    }
}

class AnimatePanel extends JPanel implements Runnable {
    Image[] picture = new Image[6];
    int totalPictures = 0;
    int current = 0;
    Thread runner;
    int pause = 800;
    String[] imageNames = { "lh0.gif", "lh1.gif", "lh2.gif", "lh3.gif" };
    
    public AnimatePanel() {
        super();
        Toolkit kit = Toolkit.getDefaultToolkit();
        for (int i = 0; i < imageNames.length; i++) {
            picture[i] = kit.getImage(imageNames[i]);
        }
        runner = new Thread(this);
        runner.start();
    }

    public void paintComponent(Graphics screen) {
        Graphics2D screen2D = (Graphics2D) screen;
        if (picture[current] != null) {
            screen2D.drawImage(picture[current], 0, 0, this);
        }
    }

    public void start() {
        if (runner == null) {
            runner = new Thread(this);
            runner.start();
        }
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (runner == thisThread) {
            repaint();
            current++;
            if (current > imageNames.length) {
                current = 0;
            }
            try {
                Thread.sleep(pause);
            } catch (InterruptedException e) { }
        }
    }

    public void stop() {
        if (runner != null) {
            runner = null;
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?