【问题标题】:How to implement sleep to display a slideshow of images如何实现睡眠以显示图像的幻灯片
【发布时间】:2011-10-14 14:59:56
【问题描述】:

我在 Java Swing 中使用 JWindows 显示图像...我让不同的 JLabels 包含我想要显示的图像。我删除以前添加的组件并添加新的组件以显示在同一个 JWindow 上。问题如下..

代码在没有睡眠功能的情况下完美运行。我可以在事件完成后在不同窗口或同一窗口上显示所有图像。但是当我使用睡眠时,在此期间什么都不会显示...

有没有办法像幻灯片一样对图像实施延迟,并在延迟之前绘制图像?

            getContentPane().remove(startLabel);
            getContentPane().add(recordLabel1, "Center");
            setVisible(true);
            try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                getContentPane().remove(recordLabel1);
                getContentPane().add(recordLabel2, "Center");
            try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                getContentPane().remove(recordLabel2);
                getContentPane().add(recordLabel3, "Center");
            try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                getContentPane().remove(recordLabel3);
                getContentPane().add(recordLabel4, "Center");
            try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                getContentPane().remove(recordLabel4);
                getContentPane().add(pausedLabel, "Center");
                setVisible(false);  

【问题讨论】:

  • 编辑:我尝试更改固定 JLabel 上的图像,而不是添加和删除组件...没有用!
  • 编辑:我还尝试切换许多不同的重叠窗口,其中包含可见和不可见的不同图像...没有用!
  • 下面的答案没有解释为什么什么也没发生。这是因为您的代码在 Swing 事件线程中运行,而当您睡眠时,您会暂停该线程。不过,线程需要更新和显示 Swing 组件,所以在它休眠时不会发生任何事情。
  • 我认为您应该阅读 java.sun.com/products/jfc/tsc/articles/threads/threads1.html 以了解 Swing 的事件处理和线程的基本工作原理。

标签: java swing sleep


【解决方案1】:

现在是使用Swing Timers 的好时机。

你应该:

  • 将您的标签/图片存储在一个数组中,而不是存储在不同的变量中
  • 按照上述教程设置计时器
  • 在计时器事件中,只需轮换您的标签数组

为此,您只需要一个额外的成员来存储您当前显示的图片编号。当计时器触发时,使用该成员从窗格中删除当前项目,增加它(以您拥有的元素总数为模),然后插入新的。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 2017-12-31
  • 2023-03-08
  • 2011-08-23
  • 2015-05-21
  • 1970-01-01
相关资源
最近更新 更多