Java 如何使用swing定时器在for循环中睡眠?
如何使用swing定时器在for循环中睡眠 对于(int j=0;j<0;i++){ 系统输出println(j); 试一试{ 睡眠(1000); }捕获(例外e){ // }Java 如何使用swing定时器在for循环中睡眠?,java,swing,timer,Java,Swing,Timer,如何使用swing定时器在for循环中睡眠 对于(int j=0;j
}我认为这个问题得到了反对票,因为:
- 不清楚问题的背景是什么和/或您正试图做什么
- 您尚未列出在发布之前尝试过的内容
- 谷歌可能会回答你的问题
for (int j = 0; j < 0; i++) {
System.out.println(j);
timer = new Timer(ONE_SECOND, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Whatever you are trying too do (ie. update progress bar)
if (/* What you are waiting for */) {
try {
Thread.sleep(1000);
} catch (Exception e) {
//
}
}
}
});
}
for(int j=0;j<0;i++){
系统输出println(j);
计时器=新计时器(1秒,新ActionListener(){
已执行的公共无效操作(操作事件evt){
//…无论您尝试做什么(即更新进度条)
如果(/*您在等待什么*/){
试一试{
睡眠(1000);
}捕获(例外e){
//
}
}
}
});
}
您的for
循环有两个语法问题
for (int j = 0; j < 0; i++) {
接下来,我们需要创建一个计时器
;初始化侦听器
,并启动
(等待进程完成)。差不多
static class MyListener implements ActionListener {
int n = 0;
Timer t;
public void setTimer(Timer t) {
this.t = t;
}
@Override
public void actionPerformed(ActionEvent e) {
if (n < 10) {
System.out.println(n++);
} else {
// Stop the Timer
t.stop();
}
}
}
public static void main(String[] args) {
MyListener mm = new MyListener();
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
Timer t = new Timer(1000, mm);
mm.setTimer(t);
t.start();
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
哈哈,什么是消极点?那是一个摆动计时器吗?否则…看起来你已经搞定了。