Swing中While循环导致前置UI更新代码未执行的问题排查
问题原因与解决方案
核心原因:Swing的UI操作和事件处理都在**事件派发线程(EDT)**中执行。你在按钮点击事件里调用了
endCheck(),其中的while循环会持续占用EDT,导致之前调用的validate()和repaint()根本没有机会被执行——EDT被循环卡死,无法处理UI渲染任务,所以看起来UI更新被跳过了。解决方案:用
javax.swing.Timer替代while循环实现定时检测,Timer的任务会在EDT中执行,不会阻塞UI线程:修改后的代码示例:
if(e.getSource() == startSixty) { milliseconds = System.currentTimeMillis(); this.remove(startButton); this.remove(beginning); this.remove(startText); this.remove(startSixty); this.add(hitButton); validate(); repaint(); // 用Swing Timer每隔100ms检查一次时间 Timer timer = new Timer(100, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { long elapsedSeconds = (System.currentTimeMillis() - milliseconds) / 1000; if (elapsedSeconds >= 10) { ((Timer)e.getSource()).stop(); // 停止定时器 // 执行结束后的UI更新 remove(hitButton); add(finishedHitCount); add(finishedMissCount); add(hitMissRatio); add(hitTimeRatio); validate(); repaint(); } } }); timer.start(); }同时可以删除原来的
endCheck()方法,Timer已替代其功能。补充说明:永远不要在EDT中执行长时间运行的代码(比如无限循环、耗时计算),这会导致UI冻结、更新失效。所有耗时操作要放到单独的后台线程,而UI更新必须回到EDT(Swing Timer的任务自动在EDT执行,无需额外处理)。
内容的提问来源于stack exchange,提问作者QMorrow
相关产品推荐
相关产品推荐

