如何在 java swing 应用程序中暂停/睡眠/等待?

2023-11-25

我正在使用 JLabel 创建动画,

public void updateLabels() {
      label.setIcon(new ImageIcon(new Paint().getScaledImage(paint[currentIndexLabel].imageCALA,300,300)));
      label_1.setIcon(new ImageIcon(new Paint().getScaledImage(paint[currentIndexLabel].imageStates,300,300)));
      label_2.setIcon(new ImageIcon(new Paint().getScaledImage(paint[currentIndexLabel].imageStrategies,300,300)));
      label_3.setIcon(new ImageIcon(new Paint().getScaledImage(paint[currentIndexLabel].imagekD,300,300)));

      currentIndexLabel++;
}

我有一个更新标签的按钮

btn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        while (currentIndexLabel != paint.length-1) {
            updateLabels();
        }
    }
});

但是,我不知道如何等待,例如 1000 毫秒,直到下一次更改。当我添加这个时:

try { Thread.sleep(1000); } catch (Exception e){}

进入我的 ActionListener:

btn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
           while (currentIndexLabel!=paint.length-1) {
             updateLabels();
             try { Thread.sleep(1000); } catch (Exception e){}
       }
    }
 });

它不工作。它只是停止了一段时间,我没有看到第一帧和最后一帧之间的变化。是否可以等待1000ms而不停止程序?当我删除 while 循环和 try 部分,然后单击我的按钮时,它变化得很好......

我怎样才能做到这一点?


Using Thread#sleep摆动应用中的方法main线程将导致 GUI 冻结(由于线程休眠,事件无法发生)。Thread#sleep摆动应用中的方法仅允许由以下人员使用摇摆工人,这在他们的#doInBackround method.

为了在 Swing 应用程序中等待(或定期执行某些操作),您必须使用摇摆计时器。看看我做的一个例子:

import java.awt.FlowLayout;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer; //Note the import

public class TimerExample extends JFrame {
    private static final int TIMER_DELAY = 1000;
    private Timer timer;

    public TimerExample () {
        super();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(200, 200);
        setLocationRelativeTo(null);
        getContentPane().setLayout(new FlowLayout());

        timer = new Timer(TIMER_DELAY, e -> {
            System.out.println("Current Time is: " + new Date(System.currentTimeMillis()));
        });
        //timer.setRepeats(false); //Do it once, or repeat it?
        JButton button = new JButton("Start");
        button.addActionListener(e -> timer.start());
        getContentPane().add(button);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new TimerExample().setVisible(true));
    }
}

按下“开始”按钮后的输出:

当前时间是: 2019 年 EET 2 月 25 日星期一 13:30:44

当前时间是: 2019 年 EET 2 月 25 日星期一 13:30:45

当前时间是: 2019 年 EET 2 月 25 日星期一 13:30:46

正如您所看到的,Timer 的动作侦听器每秒都会触发一次。

所以在你的情况下:

timer = new Timer(TIMER_DELAY, e -> {
    if (currentIndexLabel != paint.length-1) {
        upateLabels();
        timer.restart(); //Do this check again after 1000ms
    }
});
button.addActionListener(e -> timer.start());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 java swing 应用程序中暂停/睡眠/等待? 的相关文章

随机推荐