制作会自动更改图像的幻灯片

Making slideshow which will automatically change images

我在幻灯片放映方面遇到问题。我为这个程序添加了两个参数:包含图像的文件夹路径,图像重绘后的时间。 图片应以原始大小绘制,window 调整为该大小。如果某些文件不是图像,程序应该绘制 "ERROR" 语句。无论如何,该程序根本不起作用,也没有绘制任何图像。任何人都可以告诉我为什么它不绘制任何东西以及 Timer 是否是重绘图像的好方法?

public class ImagePanel extends JPanel
{

        Image img;

        private int period;
        private int n = 0;
        private File[] files;
        Timer timer;
        Dimension d;

      public ImagePanel(File dir, int period) 
      {
          this.period = period;

          files = dir.listFiles();
          loadImage(files[n++].getPath());

          timer = new Timer(period, new ActionListener()
              {
                    public void actionPerformed(ActionEvent e)
                    {
                        //Component component = (Component) e.getSource();
                        //JFrame f = (JFrame) 
                        //SwingUtilities.windowForComponent(component);
                        //f.pack();
                        if (n < files.length)
                        {
                            loadImage(files[n].getPath());
                        }
                        else
                        {
                            repaint();
                            ((Timer)e.getSource()).stop();
                        }
                        n++;
                    }
              });

          timer.start();
      }

      public void paintComponent(Graphics g) 
      {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;
        if (img != null)
            g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
      }

      private void loadImage(String imgFileName) 
      {
        img = new ImageIcon(imgFileName).getImage();
        int w = img.getWidth(this);
        int h = img.getHeight(this);
        if (w != -1 && w != 0 && h != -1 && h != 0) 
        {
          d = new Dimension(img.getWidth(this), img.getHeight(this));
        }

        revalidate();
        repaint();
      }

      @Override
      public Dimension getPreferredSize()
      {
          return new Dimension(img.getWidth(this), img.getHeight(this));
      }


 public static void main(String[] args)
 {
    JFrame frame = new JFrame();
    frame.setLayout(new GridLayout(0, 1, 0, 0));

    ImagePanel panel = new ImagePanel(new File(args[0]), Integer.parseInt(args[1]) * 1000);
    frame.add(panel);
    //frame.getContentPane().add(panel);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

 }
}

whether Timer is good way to repaint images?

是的,您应该使用 Swing Timer 来安排动画。

Anyone could tell me why it doesn't draw anything

在您的 ImagePanel class 中,您应该创建一个类似于 setImage(...) 的方法。每当您想要更改图像时,T​​imer 代码都会调用此方法。

然后在 setImage(...) 方法中你需要调用 repaint() 告诉面板重新绘制自己。