【发布时间】:2023-04-10 00:39:01
【问题描述】:
我已经起草了以下应用程序,以循环遍历字符串数组(我是初学者)。目的是使用 JLabel 在 JFrame 上显示数字 1 到 5;每秒都在变化。
当 JFrame 在屏幕上弹出时,它会奇怪地显示位于数组位置一的数字“二”。这与我的预期相反,我不知道为什么。
i 初始化为 1;存储在“temp”中;然后将其添加到 JLabel 并因此添加到 JFrame。使用这种方法是否有延迟;即到 JLabel 更新时; for循环已经推进了?或者,我知道 Java.swing 有线程问题...?
非常感谢您的帮助。
J
package testApplication;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Count {
public static void main (String args[]){
String[] numbers = {"one","two","three","four","five"};
JLabel numToDisplay = new JLabel("");
String temp;
//Initiate JFrame
JFrame frame = new JFrame("Counting Application");
frame.setSize(275,100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
for (int i=0; i < numbers.length; i++){
temp = numbers[i];
numToDisplay.setText(temp);
frame.add(numToDisplay);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
【问题讨论】:
-
您正在阻塞事件调度线程 - 请改用 Swing 计时器
标签: java arrays for-loop jframe jlabel