我的程序的想法是从之前在其他 JFrame 中保存的列表中选择一个名称。我想在标签中一个接一个地打印所有名称,它们之间有很小的延迟,然后停在其中一个名称上。问题是,如果有多个 setText
代码,则 lbl.setText("String");
不起作用。
这是我的代码的一部分:
public void actionPerformed(ActionEvent e)
{
if (RandomNames.size != 0)
{
for (int i = 0; i < 30; i++)
{
int rand = (int)(Math.random() * RandomNames.size);
stars.setText(RandomNames.list.get(rand));
try
{
Thread.sleep(100);
}
catch (InterruptedException err)
{
err.printStackTrace();
}
}
int rand2 = (int)(Math.random() * RandomNames.size);
stars.setText(RandomNames.list.get(rand2));
RandomNames.list.remove(rand2);
RandomNames.size = RandomNames.list.size();
}
if (RandomNames.list.size() == 0)
{
last.setText("\u062A\u0645 \u0638\u0647\u0648\u0631 \u062C\u0645\u064A\u0639 \u0627\u0644\u0623\u0633\u0645\u0627\u0621 \u0627\u0644\u062A\u064A \u0641\u064A \u0627\u0644\u0642\u0627\u0626\u0645\u0629 !");
}
}
最佳答案
不要使用循环或Thread.sleep
。只需使用javax.swing.Timer
。以下将导致每 1000 毫秒发生 30 次迭代。您可以根据您希望每隔几毫秒发生的情况调整 actionPerformed
中的代码。
int count = 0;
...
Timer timer = new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if (count == 30) {
((Timer)e.getSource()).stop();
} else {
int rand = (int) (Math.random()* RandomNames.size);
stars.setText(RandomNames.list.get(rand));
count++;
}
}
});
timer.start();
如果你愿意,你可以在构造函数中设置Timer
,并在另一个按钮监听器的actionPerformed
中设置start()
.
查看更多信息 How to use Swing Timers
关于java - for循环中更新JLabel的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21795183/