java - JFormatedTextField DocumentListener 引发 java.lang.IllegalStateException

标签 java swing illegalstateexception numberformatexception documentlistener

我的程序应该根据用户想要获得的产品数量打印交易价格,用户在 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/

相关文章:

java - 如何保持 fragment 中的滚动位置?

java - 什么是 swingset2

android - IllegalStateException:应用程序的 PagerAdapter 在没有调用 PagerAdapter#notifyDataSetChanged 的​​情况下更改了适配器的内容

java - 如何通过.class获取泛型类型?

javascript - Spring WebFlux 和 WebSocket

java.lang.NoClassDefFoundError : javax/servlet/http/HttpServletRequest

java - 当JFrame不断重绘时如何设置形状的渐变?

java - 按下按钮时画一个圆圈

java - 使用 MediaPlayer 在 Android 上播放默认铃声时出现非法状态异常和权限问题

java - 如果重新创建 Activity ,Android显示对话框会导致非法状态异常