使用JTextField - 无法将值转换为int

时间:2014-02-26 05:26:27

标签: java swing jtextfield parseint

我想从JComboBox获取所选值,在数据库中搜索并使用JTextField中的值更新数据库中的数量。这是代码:

    Object selected = jComboBox1.getSelectedItem();
    String album = (String)selected;
    int qty=Integer.parseInt(jTextField7.getText());
    String query2="update  productlist set QtyAvail=? " +
                "where Album=?";
        try
        {
            PreparedStatement ps2=con.prepareStatement(query2);
            ps2.setInt(1, qty);
            ps2.setString(2,album);
            int res1=ps2.executeUpdate();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

我收到了这个错误:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException:
  For input string: " 1"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at AddProductPanel.jButton2ActionPerformed(AddProductPanel.java:341)
    at AddProductPanel.access$4(AddProductPanel.java:335)
    at AddProductPanel$5.actionPerformed(AddProductPanel.java:133)

我在文本字段中输入了值“1”。

4 个答案:

答案 0 :(得分:5)

输入parseInt()的字符串中有一个空格,使用trim()

答案 1 :(得分:4)

  

我想从JComboBox获取所选值,在数据库中搜索并使用JTextField中的值更新数据库中的数量。

  • JFormattedTextFieldNumber Formatter

  • 一起使用
  • 或者更好的是使用JSpinnerSpinnerNumberModel

  • 避免在数据类型之间进行解析,可以控制输入的值(min - max - ev。范围 - 十进制形式)

答案 2 :(得分:2)

您的字符串包含空格。

在解析之前使用trim:

int qty=Integer.parseInt(jTextField7.getText().trim());

答案 3 :(得分:1)

@Nivedita Gautam:a blank之前似乎附加了1个空格。 尝试使用以下语句:

int qty = Integer.parseInt(jTextField7.getText().trim());