[英]Java Swing Image Slide Show why a picture don't change
嗨,我創建了一個ImageSlide2
類,並且只有線程,並且一次更改圖片,為什么?
我不知道為什么只一次改變圖片。 幻燈片必須一直顯示更改的圖片,這是我的代碼:
public class ImageSlide2 extends JLabel {
private Timer tm;
private int xx = 0;
String[] list = {
"C:/Users/022/workspace22/EkranLCD/res/images/1.png", //0
"C:/Users/022/workspace22/EkranLCD/res/images/3.png" //1
};
public ImageSlide2(int x, int y, int width, int height) {
setBounds(x, y, width, height);
//Call The Function SetImageSize
SetImageSize(list.length - 1);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
new Thread(new Runnable() {
public void run() {
try {
System.out.println(xx);
SetImageSize(xx);
xx += 1;
if (xx >= list.length) {
xx = 0;
}
} catch (Exception ie) {
}
}
}).start();
}
//create a function to resize the image
public void SetImageSize(int i) {
ImageIcon icon = new ImageIcon(list[i]);
Image img = icon.getImage();
Image newImg = img.getScaledInstance(Config.xSize / 2, Config.ySize / 2, Image.SCALE_SMOOTH);
ImageIcon newImc = new ImageIcon(newImg);
setIcon(newImc);
}
}
嘗試使用javax.swing.Timer更改您的方法。 像這樣:
public ImageSlide2(int x, int y, int width, int height) {
setBounds(x, y, width, height);
//Call The Function SetImageSize
SetImageSize(list.length - 1);
final Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
System.out.println(xx);
SetImageSize(xx);
xx += 1;
if (xx >= list.length) {
xx = 0;
}
} catch (Exception ie) {
}
}
});
// t.setRepeats(false); // when you want to execute it at once
t.start();
}
以下是基於線程的解決方案-您需要將睡眠添加到一個連續繪制的循環中,然后進行睡眠等:
public ImageSlide2(int x, int y, int width, int height) {
setBounds(x, y, width, height);
//Call The Function SetImageSize
SetImageSize(list.length - 1);
new Thread(new Runnable() {
public void run() {
while(true)
try {
System.out.println(xx);
SetImageSize(xx);
xx += 1;
if (xx >= list.length) {
xx = 0;
}
Thread.sleep(1000);
} catch (Exception ie) { ie.printStackTrace();
}
}
}).start();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.