我的程序应该根据用户想要获得的产品数量打印交易价格,用户在 JFormatedTextField 上键入内容,并且 documentListener 通知更改,但是当用户删除该漏洞时,程序就会终止。 `
final JFormattedTextField quantityTextField = new JFormattedTextField((Integer) null);
//Check for changes.
quantityTextField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
if(quantityTextField.getText()!=null){
totalPrice = (Integer.valueOf(quantityTextField.getText()).intValue())* unitaryPrice ;
priceToShow.setText(""+totalPrice);
}else{
totalPrice=0;
quantityTextField.setText("0");
}
}
@Override
public void removeUpdate(DocumentEvent e) { //Here is the problem the text on the field isnt equals to "" or null (when is empty)
if(quantityTextField.getText()!=null && quantityTextField.getText()!=""){
totalPrice = (Integer.valueOf(cuantityTextField.getText()).intValue())* unitaryPrice ;
priceToShow.setText(""+totalPrice);
}else{
totalPrice=0;
quantityTextField.setText("0");
}
}
@Override
public void insertUpdate(DocumentEvent e) {
System.out.println("\n++ Insert");
totalPrice = (Integer.valueOf(quantityTextField.getText()).intValue())* unitaryPrice ;
priceToShow.setText(""+totalPrice);
}
});
当用户删除后它为空时,编译器会抛出 java.lang.IllegalStateException,用于将“”转换为 int。 removeUpdate 监听器中的 if 子句应该处理文本是否为空或 null 并将总价设置为 0,但条件永远不会达到,我不知道为什么。
请帮忙。
最佳答案
将代码包装在 SwingUtilities.invokeLater()
顺便说一句 quantityTextField.getText()!="
"不起作用。使用 equals() 代替。
关于java - JFormatedTextField DocumentListener 引发 java.lang.IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21200642/