我希望在写入和删除时能够获得提示,但是在0.5秒延迟后,它会告诉我“您停止了写入/删除”。然而,只有在半秒延迟后才显示该消息,并且才会执行删除或写入操作。
我应该如何正确使用Thread.sleep(500);
?
我的当前源代码:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class TextChangedFrame extends JFrame {
JTextField textField = new JTextField("Put your text here");
JLabel label = new JLabel("You have written: ");
public TextChangedFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setLayout(new BorderLayout());
getContentPane().add(textField, BorderLayout.CENTER);
getContentPane().add(label, BorderLayout.SOUTH);
textField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
label.setText("I'm writting: " + textField.getText());
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
label.setText("I stopped writing");
}
public void removeUpdate(DocumentEvent e) {
label.setText("I'm deleting");
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
label.setText("I stopped deleting");
}
public void changedUpdate(DocumentEvent e) {
}
});
}
public static void main(String[] args) {
TextChangedFrame frame = new TextChangedFrame();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Thread.sleep(...)
。除非你想让整个应用程序休眠,否则永远不要这样做。 - Hovercraft Full Of Eelsthread.sleep(int x)
的作用,它会暂停当前线程正在执行的任何操作,持续x
毫秒(Thread.sleep(1000) = 1 秒暂停)。 - Azulflame