延迟 ActionListener 中的动作?
Delay an action within an ActionListener?
我想做什么:我想在 ActionListener 中的两个动作之间添加延迟,所以我尝试使用以下代码:
button.addActionListener(new ActionListener() {
public void actionPreformed(ActionEvent arg0) {
System.out.println("Hello");
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Goodbye");
}
};
问题:所发生的一切是 JButton 会冻结我延迟操作的时间。
我的问题: 我需要知道如何延迟以便打印 "Hello" 然后 1000 毫秒(或 1 秒)后,我希望它打印 "Goodbye".
您可以直接使用 javax.swing.Timer
:
button.addActionListener(new ActionListener() {
public void actionPreformed(ActionEvent arg0) {
System.out.println("Hello");
new Timer(1000, new ActionListener() {
@Override void actionPerformed(ActionEvent e) {
System.out.println("Goodbye");
}
}).start();
}
};
我想做什么:我想在 ActionListener 中的两个动作之间添加延迟,所以我尝试使用以下代码:
button.addActionListener(new ActionListener() {
public void actionPreformed(ActionEvent arg0) {
System.out.println("Hello");
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Goodbye");
}
};
问题:所发生的一切是 JButton 会冻结我延迟操作的时间。
我的问题: 我需要知道如何延迟以便打印 "Hello" 然后 1000 毫秒(或 1 秒)后,我希望它打印 "Goodbye".
您可以直接使用 javax.swing.Timer
:
button.addActionListener(new ActionListener() {
public void actionPreformed(ActionEvent arg0) {
System.out.println("Hello");
new Timer(1000, new ActionListener() {
@Override void actionPerformed(ActionEvent e) {
System.out.println("Goodbye");
}
}).start();
}
};