我尝试显示图像 3 秒,然后切换到 java gui,但它不起作用

i tried show image for 3 seconds and then switched in java gui but its doesnt work

我试图制作一个显示图像 3 秒然后切换它的程序,但不是显示第一个图像,而是等待然后显示第二个图像,它等待显示第一个图像,然后显示第二个图像,谢谢帮助

        JLabel image = new JLabel("");
        image.setBounds(100, 20, 125, 200);
        contentPane.add(image);
        image.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent me) {

                  image.setIcon(one);

                  try {

                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                  image.setIcon(two);

              }

            });

尝试这样的事情:

image.setIcon(one);
javax.swing.Timer timer = new Timer(3000, new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
    image.setIcon(two);
    timer.stop();
  }
});

确保使用 javax.swing.Timer 而不是 java.util.Timer,因为您正在更新 Swing UI 组件。 Swing 计时器在事件分派线程 (EDT) 上执行其回调。

话虽如此,请考虑使用 SwingWorker for long running tasks (i.e. if the image files in your example are large). The docs 的建议,使用上述方法仅执行 small/short 个任务。