我希望在用户更改文本字段中的值后立即显示消息框。目前,我需要按回车键才能弹出消息框。我的代码有什么问题吗?
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/3953208/