0

我正在尝试使用 MySQL 在 java swing 中开发 stockManager 应用程序。运行代码时,我收到以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at org.bil.service.StockManager.addNewItem(StockManager.java:355)
at org.bil.service.StockManager.actionPerformed(StockManager.java:163)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)

我附上下面的代码..它有点长..请原谅..

StockManager.java

package org.bil.service;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

import org.res.bil.PersonInfo;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.*;

public class StockManager implements ActionListener {

ArrayList itemList;
StockManagerDAO stockManagerDAO;
// Declaration
JPanel topPanel, bottomPanel;
JScrollPane scrollPane;
JFrame frame;
JMenuBar menubar = new JMenuBar();;
JMenu menu = new JMenu();
JMenuItem menuItem;
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
Image img = kit.getImage("images/icon.JPG");
String entryDate;
int itemNo;
String itemName;
double unitPrice;
double qty;
double totalPrice;
String supplier;
String remarks;
JTextField txtEntryDate;
JTextField txtItemNo;
JTextField txtItemName;
JTextField txtUnitPrice;
JTextField txtQty;
JTextField txtTotalPrice;
JTextField txtSupplier;
JTextField txtRemarks;
JButton BttnSaveAdded;
// Main
public static void main(String[] args) {

    new StockManager();
}

// Constructor
StockManager() {

    frame = new JFrame("Stock Manager");
    frame.setSize(680, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocation(screenWidth / 4, screenHeight / 4);
    frame.setIconImage(img);
    frame.show();
    userInterface();
    itemList = new ArrayList();
    stockManagerDAO = new StockManagerDAO();
}

// User Interface
public void userInterface()

{
    menubar.add(menu);
    menu = new JMenu("Options");
    menuItem = new JMenuItem("Add New Item");
    menu.add(menuItem);
    menuItem.addActionListener(this);
    menuItem = new JMenuItem("Delete Item");
    menu.add(menuItem);
    menuItem.addActionListener(this);
    menuItem = new JMenuItem("Search Item");
    menu.add(menuItem);
    menuItem.addActionListener(this);
    menuItem = new JMenuItem("Sort Item");
    menu.add(menuItem);
    menuItem.addActionListener(this);
    menuItem = new JMenuItem("View All Item");
    menu.add(menuItem);
    menuItem.addActionListener(this);
    menuItem = new JMenuItem("Backup Item");
    menu.add(menuItem);
    menuItem.addActionListener(this);
    menubar.add(menu);
    menu = new JMenu("Help");
    menuItem = new JMenuItem("Help Contents");
    menu.add(menuItem);
    menuItem.addActionListener(this);
    menuItem = new JMenuItem("About");
    menu.add(menuItem);
    menuItem.addActionListener(this);
    menubar.add(menu);
    frame.setJMenuBar(menubar);
    JPanel topPanel = new JPanel();
    JPanel bottomPanel = new JPanel();
    // Add Buttons To Bottom Panel
    JButton addItem = new JButton("Add New Item");
    JButton deleteItem = new JButton("Delete Item");
    JButton searchItem = new JButton("Item");
    JButton sortItem = new JButton("Sort Item");
    JButton viewAllItems = new JButton("View AllItem");

    JLabel label = new JLabel(
            "<HTML><FONT FACE = ARIALSIZE = 2><B>Use The options below and In The Menu To Manage Stock");
    // Add Action Listeners
    addItem.addActionListener(this);
    deleteItem.addActionListener(this);
    searchItem.addActionListener(this);
    sortItem.addActionListener(this);
    viewAllItems.addActionListener(this);
    topPanel.add(label);
    bottomPanel.add(addItem);
    bottomPanel.add(deleteItem);
    bottomPanel.add(searchItem);
    bottomPanel.add(sortItem);
    bottomPanel.add(viewAllItems);
    frame.getContentPane().add(topPanel, BorderLayout.NORTH);
    frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
    frame.setResizable(false);

}

public void actionPerformed(ActionEvent ae) {
    if (ae.getActionCommand() == "Add New Item") {
        //totalPrice = unitPrice * qty;
        // txtTotalPrice= totalPrice;
        addNewItem();

    }

    else if (ae.getActionCommand() == "Search Item") {
        searchItem();

    }

    else if (ae.getActionCommand() == "Sort Contacts") {
        sortItems();

    }

    else if (ae.getActionCommand() == "Delete Item") {
        deleteItem();

    }

    else if (ae.getActionCommand() == "View All Items") {

        viewAllItemsInStock();

    }

    else if (ae.getActionCommand() == "About") {
        JOptionPane.showMessageDialog(frame,
         "About StockManager:Helps to manage the stock by adding,deleting,searching and displaying items in the stock,",null, JOptionPane.INFORMATION_MESSAGE);

    } else if (ae.getActionCommand() == "Help Contents") {
        showHelp();

    } else if (ae.getActionCommand() == "Backup Contacts") {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        chooser.setMultiSelectionEnabled(false);

        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.showSaveDialog(frame);
        FileOutputStream bfout = null;
        FileInputStream bfin = null;
        String filename = null;

        int p;

        try {
            filename = chooser.getSelectedFile().getPath();
        } catch (Exception e) {
        }

        try {
            bfout = new FileOutputStream(filename + "/data.dat");
        } catch (Exception e) {

        }
        try {
            bfin = new FileInputStream("data/data.dat");
        } catch (Exception e) {

        }

        try {
            do {
                p = bfin.read();
                if (p != -1)
                    bfout.write(p);
            } while (p != -1);
        } catch (Exception e) {

        }

    }

}

private void showHelp() {
    // TODO Auto-generated method stub

}

private void viewAllItemsInStock() {
    /*ResultSet rs= st.executeQuery("Select * from test");
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    for (int i = 1; i <= columns; i++) {
    columnNames.addElement( md.getColumnName(i) );
    }
    while (rs.next()) {
    Vector row = new Vector(columns);
    for (int i = 1; i <= columns; i++) {
    row.addElement( rs.getObject(i) );
    }
    data.addElement( row );
    }
    rs.close();
    st.close();
    }
    catch(Exception e) {}
    JFrame tab=new JFrame();
    JTable table = new JTable(data, columnNames);
    JScrollPane scrollPane = new JScrollPane( table );
    tab.add( scrollPane );
    tab.setVisible(true); 
    tab.setSize(300,100);
    }
    });
    }*/

}

private void deleteItem() {
    // TODO Auto-generated method stub

}

private void sortItems() {
    // TODO Auto-generated method stub

}

private void searchItem() {
    // TODO Auto-generated method stub

}

public void addItemFrame() {
    JFrame newFrame;
    newFrame = new JFrame("Add New");
    newFrame.setSize(220, 250);
    newFrame.setResizable(false);
    newFrame.setIconImage(img);

    JLabel lblEntryDate = new JLabel("Item EntryDate: ");
    JLabel lblItemNo = new JLabel("Item No: ");
    JLabel lblItemName = new JLabel("Item Name: ");
    JLabel lblUnitPrice = new JLabel("Item UnitPrice: ");
    JLabel lblQty = new JLabel("Item Qty: ");
    JLabel lblTotalPrice = new JLabel("Item TotalPrice: ");
    JLabel lblSupplier = new JLabel("SupplierDetails: ");
    JLabel lblRemarks = new JLabel("Remarks: ");
    JLabel lblEmpty1 = new JLabel("");
    JLabel lblEmpty2 = new JLabel("");

    txtEntryDate = new JTextField(10);
    txtItemNo = new JTextField(10);
    txtItemName = new JTextField(10);
    txtUnitPrice = new JTextField(10);
    txtQty = new JTextField(10);
    txtTotalPrice = new JTextField(10);
    txtSupplier = new JTextField(10);
    txtRemarks = new JTextField(10);

    JButton bttnAdd = new JButton("Save");
    JButton bttnCancel = new JButton("Save Added!");

    bttnAdd.addActionListener(this);
    bttnCancel.addActionListener(this);

    JPanel centerPane = new JPanel();
    JPanel bottomPane = new JPanel();

    centerPane.add(lblEntryDate);
    centerPane.add(txtEntryDate);
    centerPane.add(lblItemNo);
    centerPane.add(txtItemNo);
    centerPane.add(lblItemName);
    centerPane.add(txtItemName);
    centerPane.add(lblUnitPrice);
    centerPane.add(txtUnitPrice);
    centerPane.add(lblQty);
    centerPane.add(txtQty);
    centerPane.add(lblTotalPrice);
    centerPane.add(txtTotalPrice);
    centerPane.add(lblSupplier);
    centerPane.add(txtSupplier);
    centerPane.add(lblRemarks);
    centerPane.add(txtRemarks);
    bottomPane.add(bttnAdd);
    bottomPane.add(bttnCancel);
    centerPane.setLayout(new GridLayout(0, 2));

    newFrame.getContentPane().add(centerPane, BorderLayout.CENTER);

    newFrame.getContentPane().add(bottomPane, BorderLayout.SOUTH);
    newFrame.setLocation(screenWidth / 4, screenHeight / 4);
    newFrame.show();

}

public void addNewItem() {
    addItemFrame();
    entryDate = txtEntryDate.getText();
    itemNo = Integer.parseInt(txtItemNo.getText());
    itemName = txtItemName.getText();
    unitPrice = Double.parseDouble(txtUnitPrice.getText());
    qty = Double.parseDouble(txtQty.getText());
    totalPrice = unitPrice * qty;
    supplier = txtSupplier.getText();
    remarks = txtRemarks.getText();

    if (itemName.equals("")) {
        JOptionPane.showMessageDialog(null, "Please enter Item name.");
    }
    if (txtUnitPrice.getText() == "") {
        JOptionPane.showMessageDialog(null,
                "Please enter UnitPrice for the item");
    }
    if (txtQty.getText() == "") {
        JOptionPane.showMessageDialog(null,
                "Please enter Quantity of item to be added");
    } else {

        Items item = new Items(entryDate, itemNo, itemName, unitPrice, qty,
                totalPrice, supplier, remarks);
        stockManagerDAO.addNewItem(item);
        JOptionPane.showMessageDialog(null, "Person Saved");
    }
}

}

项目.java

public class Items
{
  String entryDate;
   int itemNo;
   String itemName;
   double unitPrice;
   double qty;
   double totalPrice;
   String supplier;
   String remarks;

  // default constructor
  public Items()
  {       
    entryDate ="" ;
    itemNo = 0;
    itemName="";
    unitPrice=0;
    qty=0;
    totalPrice=0;
    supplier="";
   remarks="";
  }

public Items(String entryDate,int itemNo,String itemName,double unitPrice,double qty,double totalPrice,String supplier,String remarks)
{
    this.entryDate = entryDate;
    this.itemNo = itemNo;
    this.itemName = itemName;
    this.unitPrice = unitPrice;
    this.qty =qty;
    this.totalPrice=totalPrice;
    this.supplier=supplier;
    this.remarks=remarks;
} 
//getter and setter methods
   }

StockManagerDAO.java

package org.bil.service;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.res.bil.PersonInfo;



class StockManagerDAO
{
private ArrayList itemList;
private String userid = "root";
private String password = "sa";
static String url = "jdbc:mysql://localhost/test";; 
private Connection con;

public void StockManagerDAO()
{
    itemList = new ArrayList();
    getConnection();        //Create Connection to the Oracle Database
}

public Connection getConnection(){

    try {
        Class.forName("com.mysql.jdbc.Driver"); 

    } catch(java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, userid, password);
    } catch(SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }

    return con;
}

/*public ArrayList searchItem(String name)
{
    try {
        String sql = "SELECT * FROM Item WHERE name like '%"+name+"%'";

        // Create a prepared statement
        Statement s = con.createStatement();

        ResultSet rs = s.executeQuery(sql);

        String itemname = "";
        String itemno = "";
       ........

        while(rs.next())
        {
            id = rs.getInt("id");
            pname = rs.getString("name");
            address = rs.getString("address");
            phone = rs.getInt("phone");
            email = rs.getString("email");

            //Create a Item object
            PersonInfo person = new PersonInfo(id, pname, address, phone, email);

            //Add the person object to array list
            personsList.add(person);
        }
    }
    catch(Exception e){
        System.out.println(e);
    }

    return personsList;
} 
*/
public void addNewItem(Items item) {

    try
    {

        String sql = "INSERT INTO stock(ItemNo ,ItemEntryDate, ItemName, ItemUnitPrice, ItemQty, ItemTotalPrice,ItemSupplier, ItemRemarks) VALUES (?,?,?,?,?,?,?,?) ";

        // Create a Preparedstatement
        PreparedStatement ps = con.prepareStatement(sql);

        ps.setInt(1,item.getItemNo());
        ps.setString(2, item.getEntryDate());
        ps.setString(3, item.getItemName());
        ps.setDouble(4, item.getUnitPrice());
        ps.setDouble(5, item.getQty());
        ps.setDouble(6, item.getTotalPrice());
        ps.setString(7, item.getSupplier());
        ps.setString(8, item.getRemarks());

        ps.executeUpdate();
    }
    catch(Exception e){
        System.out.println(e);
    }
// TODO Auto-generated method stub

}

}

..请帮我...

4

2 回答 2

1

看起来您正在尝试将空字符串 ( "") 解析为整数 (in Integer.parseInt(txtItemNo.getText())in StockManager.addNewItem())。

您将需要确保 的内容不为空,或者更好的是,在解析无效字符串时txtItemNo捕获。NumberFormatException

于 2012-05-16T13:00:16.803 回答
1

这意味着您txtItemNo没有文本,在解析之前检查它并在它无效时显示错误(或捕获异常并在 catch 块中显示错误)

于 2012-05-16T13:05:36.930 回答