how to auto change image in java swing?

前端 未结 2 1041
灰色年华
灰色年华 2020-12-12 05:42

Hi i am creating a java desktop application where i want to show image and i want that all image should change in every 5 sec automatically i do not know how to do this

2条回答
  •  温柔的废话
    2020-12-12 06:11

    In this example, a List holds each image selected from a List. At each step of a javax.swing.Timer, the list of images is shuffled, and each image is assigned to a label.

    image

    import java.awt.EventQueue;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import javax.swing.UIManager;
    
    /**
     * @see http://stackoverflow.com/a/22423511/230513
     * @see http://stackoverflow.com/a/12228640/230513
     */
    public class ImageShuffle extends JPanel {
    
        private List list = new ArrayList();
        private List labels = new ArrayList();
        private Timer timer = new Timer(1000, new ActionListener() {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                update();
            }
        });
    
        public ImageShuffle() {
            this.setLayout(new GridLayout(1, 0));
            list.add(UIManager.getIcon("OptionPane.errorIcon"));
            list.add(UIManager.getIcon("OptionPane.informationIcon"));
            list.add(UIManager.getIcon("OptionPane.warningIcon"));
            list.add(UIManager.getIcon("OptionPane.questionIcon"));
            for (Icon icon : list) {
                JLabel label = new JLabel(icon);
                labels.add(label);
                this.add(label);
            }
            timer.start();
        }
    
        private void update() {
            Collections.shuffle(list);
            int index = 0;
            for (JLabel label : labels) {
                label.setIcon(list.get(index++));
            }
        }
    
        private void display() {
            JFrame f = new JFrame("ImageShuffle");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(this);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new ImageShuffle().display();
                }
            });
        }
    }
    

提交回复
热议问题