【发布时间】:2016-10-12 22:29:50
【问题描述】:
一个问题:有一个带有单个按钮的简单 GUI 应用程序,当我按下按钮时它应该打印一条消息,2 秒后它应该打印另一条消息,但是当我使用 Thread.sleep(x);它不执行上面的代码并等待,这是代码:
private void button1(java.awt.event.ActionEvent evt){
System.out.println("lol 1");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
System.out.println("error");
}
System.out.println("lol 2");
}
但这并不像我想要的那样工作.. 因为它等待 2 秒,然后打印 lol 1 和 lol 2。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
PSCGenerator ps = new PSCGenerator();
String pin = jTextField1.getText();
String msg[] = {"Cracking the database...\n","Database Cracked succesfully!\n","Running the exploit...\n","Passing '"+pin+"' to the exploit..\n","New code succesfully spoofed!\n"};
int time[] = {2000,1400,1000,2500};
int x=0;
long k=2000;
jTextArea1.append(msg[x]);
try {
Thread.sleep(k);
} catch (InterruptedException ex) {
Logger.getLogger(PSCGUI.class.getName()).log(Level.SEVERE, null, ex);
}
//creando un sistema che aspetta qualche secondo prima di continuare per la falsa 控制台 System.out.println("大声笑"); }
【问题讨论】:
-
我对此表示怀疑。发布一个最小的、完整的程序来重现问题。我的猜测是你并没有真正使用 System.out.println(),而是试图在你的 UI 中显示文本。永远不要使用 sleep() 冻结 UI 线程。使用 javax.swing.Timer。这个问题已经被问了一千次了,但我懒得找到最好的副本。阅读有关并发的摇摆教程。