1
weightField.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (!((c >= '0') && (c <= '9') || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) {
              getToolkit().beep();
              e.consume();
            }
            if(serviceTypeComboBox.getSelectedIndex() == 0 && letterTypeComboBox.getSelectedIndex() == 0){
                priceField.setText(Integer.toString((Integer.parseInt(weightField.getText())/500) * 23000));
            }else if(serviceTypeComboBox.getSelectedIndex() == 0 && letterTypeComboBox.getSelectedIndex() == 1){
                priceField.setText(Integer.toString((Integer.parseInt(weightField.getText())/500) * 40000));
            }else if(serviceTypeComboBox.getSelectedIndex() == 1 && letterTypeComboBox.getSelectedIndex() == 0){
                priceField.setText(Integer.toString((Integer.parseInt(weightField.getText())/500) * 11000));
            }else if(serviceTypeComboBox.getSelectedIndex() == 1 && letterTypeComboBox.getSelectedIndex() == 1){
                priceField.setText(Integer.toString((Integer.parseInt(weightField.getText())/500) * 25000));
            }
        }});

我不知道为什么我在键入键时收到 java.lang.NumberFormatException ...:线程“AWT-EventQueue-0”中的异常 java.lang.NumberFormatException:对于输入字符串:“”

4

2 回答 2

3

仅根据您的代码:

 weightField.getText()

返回空字符串可以触发异常。验证你在那里得到一个值。我还建议您尝试/捕获该异常,以通知似乎在 TextField 中输入值的用户。

于 2013-11-01T10:39:22.610 回答
2

由于您没有括号,因此您的逻辑运算等效于:

! (c >= '0' && 
  (c <= '9' || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE) )

要让非数字/退格/删除不会进入您的 beep() if 块,您只需输入:

  • ascii 码大于 48 ('0') 的字符 - 任何字母字符或
  • c > '9' && c == KeyEvent.VK_BACK_SPACE && c == KeyEvent.VK_DELETE)

由于它是 OR,您只需要输入一个字母字符。

于 2013-11-01T10:45:50.030 回答