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

代码如下
  1. //文件名:Demo4.java
  2. package com.liuyanzhao;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6. public class Demo4 extends JFrame {
  7.     MyJPanel mp;
  8.     int index;
  9.     ImageIcon[] imgs = {
  10.             new ImageIcon("src/images/1.jpg"),
  11.             new ImageIcon("src/images/2.jpg"),
  12.             new ImageIcon("src/images/3.jpg"),
  13.             new ImageIcon("src/images/4.jpg"),
  14.             new ImageIcon("src/images/5.jpg"),
  15.             new ImageIcon("src/images/6.jpg"),
  16.             new ImageIcon("src/images/7.jpg"),
  17.             new ImageIcon("src/images/8.jpg"),
  18.         };
  19.     public Demo4() {
  20.         mp = new MyJPanel();
  21.         this.add(mp);
  22.         this.setExtendedState(JFrame.MAXIMIZED_BOTH);
  23.         this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  24.         this.setTitle("窗口");
  25.         this.setVisible(true);
  26.         Timer timer = new Timer(500,new ActionListener() {
  27.             @Override
  28.             public void actionPerformed(ActionEvent e) {
  29.                 mp.repaint();
  30.             }
  31.         });
  32.         timer.start();
  33.     }
  34.     public static void main(String[] args) {
  35.         new Demo4();
  36.     }
  37.     class MyJPanel extends JPanel{
  38.         @Override
  39.         public void paint(Graphics g) {
  40.             super.paint(g);
  41.             g.drawImage(imgs[index%imgs.length].getImage(), 00,this);
  42.             index++;
  43.         }
  44.     }
  45. }
要先在src目录下新建images文件夹,里面放图片,文件名如上 效果图是这组图片自动循环播放 本文地址:https://liuyanzhao.com/4179.html 转载请注明

发表评论

目前评论:2