Java swing实现一组图片自动轮播

代码如下

 //文件名:Demo4.java
    package com.liuyanzhao;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Demo4 extends JFrame {
        MyJPanel mp;
        int index;
        ImageIcon[] imgs = {
                new ImageIcon("src/images/1.jpg"),
                new ImageIcon("src/images/2.jpg"),
                new ImageIcon("src/images/3.jpg"),
                new ImageIcon("src/images/4.jpg"),
                new ImageIcon("src/images/5.jpg"),
                new ImageIcon("src/images/6.jpg"),
                new ImageIcon("src/images/7.jpg"),
                new ImageIcon("src/images/8.jpg"),
            };
        public Demo4() {
            mp = new MyJPanel();
            this.add(mp);
            this.setExtendedState(JFrame.MAXIMIZED_BOTH);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            this.setTitle("窗口");
            this.setVisible(true);
            Timer timer = new Timer(500,new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    mp.repaint();
                }
            });
            timer.start();
        }
        public static void main(String[] args) {
            new Demo4();
        }
        class MyJPanel extends JPanel{
            @Override
            public void paint(Graphics g) {
                super.paint(g);
                g.drawImage(imgs[index%imgs.length].getImage(), 0, 0,this);
                index++;
            }
        }
    }

要先在src目录下新建images文件夹,里面放图片,文件名如上

效果图是这组图片自动循环播放


本文链接:https://liuyanzhao.com/4179.html

你可能感兴趣的:(Java,Java基础)