java swing暂停继续_如何在Java Swing应用程序中暂停/睡眠/等待?

在Java Swing应用程序中,直接使用Thread#sleep会导致GUI界面冻结。正确的做法是利用Swing计时器(javax.swing.Timer)来实现等待或定时执行任务。例如,创建一个定时器并在动作事件中更新标签,当标签未达到最大值时,通过timer.restart()实现继续执行。这样可以避免界面无响应并实现暂停/继续功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小编典典

Thread#sleep在 主 线程中的swing应用程序中使用method

会导致GUI冻结(因为该线程处于睡眠状态,因此无法发生事件)。Thread#sleepSwing应用程序中的Swing方法仅允许SwingWorkers使用,并且只能在其#doInBackround方法中使用。

为了在Swing应用程序中等待(或定期执行某些操作),您将必须使用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年2月25日星期一13:30:44

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

当前时间是:EET 2019星期一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());

2020-09-15

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值