?? activeimagesjapplet.java
字號:
//【例8.6】 圖像的動畫設計。
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
public class ActiveImagesJApplet extends JApplet implements Runnable,ActionListener
{
private Image[] images; //圖像數組
private int index; //圖像數組下標
private Thread athread; //線程
private int sleeptime; //線程sleep時間
private String graphfile; //圖像文件名
private int graphcount; //圖像張數
private JButton button_start,button_stop; //啟動和停止按鈕
public void init()
{
this.index=0;
this.athread=null;
this.sleeptime = Integer.parseInt(this.getParameter("sleeptime")); //獲得參數
this.graphfile = this.getParameter("graphfile");
this.graphcount = Integer.parseInt(this.getParameter("graphcount"));
this.images = new Image[this.graphcount];
String fname = this.graphfile;
int j = fname.indexOf(".");
for (int i=0;i<this.graphcount;i++) //所有圖像裝入數組
{
fname = fname.substring(0,j-1)+i+fname.substring(j); //拼接其他圖像的文件名
images[i] = this.getImage(this.getDocumentBase(),"Images/"+fname);
}
JPanel panel = new JPanel();
button_start = new JButton("Start");
panel.add(button_start);
button_start.addActionListener(this);
button_stop = new JButton("Stop");
panel.add(button_stop);
button_stop.addActionListener(this);
this.setLayout(new BorderLayout());
this.add(panel,"South");
}
public void update(Graphics g)
{
g.drawImage(this.images[this.index],0,0,this);
}
public void start()
{
if (athread == null)
{
athread = new Thread(this);
athread.start(); //線程啟動
button_start.setEnabled(false);
button_stop.setEnabled(true);
}
}
public void stop()
{
if (athread != null)
{
athread.interrupt(); //線程中斷
athread = null;
button_start.setEnabled(true);
button_stop.setEnabled(false);
}
}
public void run()
{
while (true)
{
index = (index+1) % images.length; //下一幅圖像的下標
repaint();
try
{
athread.sleep(this.sleeptime);
}
catch (InterruptedException e)
{ //中斷時拋出
break; //退出循環
}
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==button_start) //單擊Start按鈕時
this.start(); //調用執行當前Applet對象的start()方法
if (e.getSource()==button_stop) //單擊Stop按鈕時
this.stop(); //調用執行當前Applet對象的stop()方法
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -