我想要做什么:我想在 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();
}
};
关于java - 延迟 ActionListener 中的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31844004/