用Java写出一个图片展示,自动切换代码
时间: 2024-02-16 08:02:42 浏览: 72
以下是一个基于Java Swing GUI库的图片轮播展示的自动切换代码示例:
```java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ImageSlider extends JFrame implements ActionListener {
private JPanel panel;
private Timer timer;
private int index = 0;
private String[] imagePaths = {"path/to/image1.jpg", "path/to/image2.jpg", "path/to/image3.jpg"};
public ImageSlider() {
setTitle("Image Slider");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
add(panel);
timer = new Timer(3000, this);
timer.start();
setVisible(true);
}
public static void main(String[] args) {
new ImageSlider();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == timer) {
index = (index + 1) % imagePaths.length;
ImageIcon imageIcon = new ImageIcon(imagePaths[index]);
JLabel label = new JLabel(imageIcon);
panel.removeAll();
panel.add(label);
panel.revalidate();
panel.repaint();
}
}
}
```
在这个示例中,使用了JFrame作为窗口容器,JPanel作为图片容器,Timer作为自动切换计时器,ImageIcon和JLabel用于展示图片。在actionPerformed方法中,每隔3秒钟自动切换到下一张图片,并将其展示在JPanel上。
阅读全文