栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

Thread#sleep
线程中的swing应用程序中使用method
会导致GUI冻结(因为该线程处于睡眠状态,因此无法发生事件)。
Thread#sleep
Swing应用程序中的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 importpublic 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());


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/486287.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号