我想知道我什么时候写,什么时候删除,但是,延迟 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);
}
}