Java Swing Image Slide显示为什么图片不会改变

时间:2016-09-26 07:07:46

标签: java image swing thread-sleep

您好我创建了一个类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);
    }
}

2 个答案:

答案 0 :(得分:1)

尝试使用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();
}

答案 1 :(得分:1)

基于线程的解决方案如下 - 您需要在一个连续绘制然后睡眠等的循环中添加睡眠:

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

}