Search code examples
javaimageswingthread-sleep

Java Swing Image Slide Show why a picture don't change


Hi I create a class ImageSlide2 and I have thread and only one time a picture change why ?

I don't know why only time a picture change. The slide show have to all time display a changed picture This is my code :

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);
    }
}

Solution

  • A solution based on thread is the following - you need to add the sleep in a loop that continuously paints and then sleeps etc:

    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();
    
    }