本文介绍了如何在Java Swing应用程序中暂停/睡眠/等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JLabel创建动画,

I'm creating an animation using 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++;
}

并且我有一个用于更新标签的按钮

and I have a button that updates the labels

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

但是,我不知道如何等待(例如1000毫秒)直到下一次更改.当我添加此内容时:

But, I don't know how to wait, say for example 1000ms, until next change. When I add this:

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

进入我的ActionListener:

into my 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循环并尝试部分时,单击我的按钮,它的变化非常好...

its not working. It just stopping for a while and I don't see changes between the first and last frames. Is it possibile to Wait 1000ms without stopping the program? When I delete the while loop and try section, and click my button it is changing pretty well...

我该怎么做?

推荐答案

main 线程中的swing应用程序中使用Thread#sleep方法将导致GUI冻结(由于该线程处于休眠状态,因此无法进行事件处理)地方).仅允许 SwingWorkers ,并通过他们的#doInBackround方法.

Using Thread#sleep method in swing applications in main thread will cause the GUI to freeze (since the thread sleeps, events cannot take place). Thread#sleep method in swing applications is only allowed to be used only by SwingWorkers, and this in their #doInBackround method.

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

In order to wait in a swing application (or do something periodically), you will have to use a Swing Timer. Take a look at an example i have made:

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));
    }
}

在开始"之后的输出.按下按钮:

Output after "Start" button is pressed:

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

Current Time is: Mon Feb 25 13:30:45 EET 2019

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

Current Time is: Mon Feb 25 13:30:46 EET 2019

如您所见,Timer的动作侦听器每秒触发一次.

As you can see, Timer's action listener fires every second.

所以在您的情况下:

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());

这篇关于如何在Java Swing应用程序中暂停/睡眠/等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 17:19