我希望在用户更改文本字段中的值后立即显示消息框。目前,我需要按 Enter 键才能弹出消息框。我的代码有什么问题吗?
textField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (Integer.parseInt(textField.getText())<=0){
JOptionPane.showMessageDialog(null,
"Error: Please enter number bigger than 0", "Error Message",
JOptionPane.ERROR_MESSAGE);
}
}
}
如有任何帮助,我们将不胜感激!
最佳答案
向基础文档添加一个监听器,该监听器是自动为您创建的。
// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
if (Integer.parseInt(textField.getText())<=0){
JOptionPane.showMessageDialog(null,
"Error: Please enter number bigger than 0", "Error Message",
JOptionPane.ERROR_MESSAGE);
}
}
});
关于java - JTextField 的值更改监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58507491/