计时器结束后如何在重复结构中设置标签位置?
How to set a Label position after a timer ends, in a repetitive structure?
我有这段代码。它移动棋盘上的棋子。
while(i<end)
{
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println(e);
}
Label.setBounds(x+i, y, xsize, ysize);
i++;
}
我的问题:
在所有时间(end
秒)过去之后,标签仅设置一次。
也尝试过:
1:
while(i<end)
{
for(int v;v<9999999;v++);
Label.setBounds(x+i, y, xsize, ysize);
i++;
}
2:
while(i<end)
{
for(int v;v<9999999;v++)
{
Label.setBounds(x+i, y, xsize, ysize);
}
i++;
}
结果相同。
The Label gets set only once, after all the time(end seconds) passes.
问题是 Thread.sleep(...)
是从 Event Dispatch Thread (EDT)
调用的,这会阻止 GUI 在循环执行完成之前重新绘制自身。
不要在 EDT
上使用 Thread.sleep()
。
阅读有关 Concurrency 的 Swing 教程部分,了解有关为什么会发生这种情况的更多信息。
简单的解决方案是使用 Swing Timer
来安排事件。本教程还有一个关于 How to Use a Swing Timer
的部分,其中包含一个可帮助您入门的工作示例。
Read the section from the Swing tutorial on Concurrency for more information on why this happens.
使用 javax.swing.Timer
我将代码修改为这种形式:
int delay = 1000;
ActionListener taskPerformer = (ActionEvent evt) ->
{
Label.setBounds(x+1, y, xsize, ysize);
if(condition)
{
timer.stop();
}
};
timer = new Timer(delay, taskPerformer);
timer.setRepeats(true);
timer.start();
它现在可以正常工作了。
我有这段代码。它移动棋盘上的棋子。
while(i<end)
{
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println(e);
}
Label.setBounds(x+i, y, xsize, ysize);
i++;
}
我的问题:
在所有时间(end
秒)过去之后,标签仅设置一次。
也尝试过:
1:
while(i<end)
{
for(int v;v<9999999;v++);
Label.setBounds(x+i, y, xsize, ysize);
i++;
}
2:
while(i<end)
{
for(int v;v<9999999;v++)
{
Label.setBounds(x+i, y, xsize, ysize);
}
i++;
}
结果相同。
The Label gets set only once, after all the time(end seconds) passes.
问题是 Thread.sleep(...)
是从 Event Dispatch Thread (EDT)
调用的,这会阻止 GUI 在循环执行完成之前重新绘制自身。
不要在 EDT
上使用 Thread.sleep()
。
阅读有关 Concurrency 的 Swing 教程部分,了解有关为什么会发生这种情况的更多信息。
简单的解决方案是使用 Swing Timer
来安排事件。本教程还有一个关于 How to Use a Swing Timer
的部分,其中包含一个可帮助您入门的工作示例。
Read the section from the Swing tutorial on Concurrency for more information on why this happens.
使用 javax.swing.Timer
我将代码修改为这种形式:
int delay = 1000;
ActionListener taskPerformer = (ActionEvent evt) ->
{
Label.setBounds(x+1, y, xsize, ysize);
if(condition)
{
timer.stop();
}
};
timer = new Timer(delay, taskPerformer);
timer.setRepeats(true);
timer.start();
它现在可以正常工作了。