一个问题:有一个简单的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 console 的System.out.println("洛尔&#34); }
答案 0 :(得分:0)
您可以使用计时器
private void button1(java.awt.event.ActionEvent evt){
Timer timer = new Timer(ms_you_wanna_wait, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// do your thing here
}
});
timer.setRepeats(false);
timer.start();
}
[编辑]看到你遇到这么多麻烦,我在这里放了一个小样本:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Swing extends JFrame {
JTextArea area;
public Swing() {
initUI();
}
public final void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
area = new JTextArea();
area.setBounds(10, 60, 80, 30);
panel.add(area);
JButton jButton = new JButton("Click");
jButton.setBounds(90, 60, 80, 30);
jButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
delayedAction();
}
});
panel.add(jButton);
setTitle("Quit button");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Swing ex = new Swing();
ex.setVisible(true);
}
public void delayedAction(){
String pin = area.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;
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO add your handling code here:
//PSCGenerator ps = new PSCGenerator();
area.append(msg[x]);
}
});
timer.setRepeats(false);
timer.start();
}
}