預先讀取圖檔,有進度表顯示目前已讀取的進度,讀取完畢後依照順序顯示圖片,每秒切換一張圖片,循環顯示這些圖片。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Slider extends JPanel
implements Runnable, ActionListener
{
// 這裡是要修改的檔案張數
final int readed_img = 30;
private Image[] image = new Image[readed_img];
private int nowindx;
private Image nowimg;
private int State;
private javax.swing.Timer gtimer = new javax.swing.Timer(1000 ,this);
private MediaTracker tracker = new MediaTracker(this);
private Font FS = new Font("標準楷",Font.BOLD,35);
Slider () {
setLayout(null);
setPreferredSize(new Dimension(800,600));
setDoubleBuffered(true);
for (int i=0 ; i < readed_img ; i++) {
// 這裡是要修改的圖檔檔名
image[i] = Tool.getImage("img/gurumins ("+i+").jpg");
tracker.addImage(image[i], i%5);
}
State = LODING_STATE;
new Thread(this).start();
}
public void run() {
System.out.println("Loading image....");
try {
for (int i=0 ; i < readed_img ; i++) {
tracker.waitForID(i%5);
now_percent ++;
repaint();
// 這裡是delay的時間
Thread.sleep(100);
}
System.out.println("Loading finish....");
State = SLIDING_STATE;
nowimg = image[0];
gtimer.start();
repaint();
} catch (InterruptedException e) {
System.err.println("Loading Image Error Occur");
}
}
public void actionPerformed(ActionEvent e) {
nowindx = (nowindx+1) % readed_img;
nowimg = image[nowindx];
repaint();
}
public void update (Graphics g) {
paint(g);
}
private int now_percent = 0;
final int LODING_STATE = 1;
final int SLIDING_STATE = 2;
public void paintComponent(Graphics g) {
g.clearRect(0,0,800,600);
switch (State) {
case LODING_STATE:
g.setFont(FS);
g.setColor(Color.black);
g.drawString("Lodaing .....", 110, 300);
for (int i=0 ; i < now_percent ; i++) {
g.setColor(Color.yellow);
// 這裡是可能要修改的進度列拓展寬度
g.fillRoundRect(100+i*20, 400, 20, 50, 4, 4);
}
break;
case SLIDING_STATE:
g.drawImage(nowimg, 0, 0, this);
g.setFont(FS);
g.setColor(Color.blue);
g.drawString("Now Slider = "+nowindx, 30, 300);
break;
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Slider Demo");
Slider pn = new Slider();
f.setContentPane(pn);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.pack();
f.setVisible(true);
}
}
class Tool {
static public Image getImage(String name) {
java.awt.Image img;
java.net.URL url;
try {
url = Tool.class.getResource(name);
img = Toolkit.getDefaultToolkit().getImage(url);
return img;
} catch (Exception e) {
System.err.println("Cannot find Image file:"+name);
return null;
}
}
}
[REF]http://codingnote.blogspot.com/2007/07/javaslider-demo.html
沒有留言:
張貼留言