0

Having problem populating the JTable with contents from MySQL. First, it works when I output the contents of the table on console (system.out). The Error: NullPointerException happens when I try display it on JTable.

Code:

import javax.swing.table.DefaultTableModel;
import java.sql.*;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;

public class ProductTable extends javax.swing.JFrame {

public ProductTable() {

     try{
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory_db","root","");

     }catch(Exception ex){
        System.out.println("Error: "+ex);
     }    
     try{
       String query = "SELECT * FROM items_in_hand";
       st = con.prepareStatement(query);
       rs = st.executeQuery(query);
       System.out.println("Records from Inventory Database:");
       itemTable.setModel(DbUtils.resultSetToTableModel(rs)); //this line here causes the error
       while(rs.next()){

            String iname = rs.getString("ItemName");
            String price = rs.getString("Price");
            String qty = rs.getString("Quantity");
            System.out.println("Item: "+ iname +"  Price (each): "+price+"  Quantity: "+qty);
       }       
    }
    catch(Exception ex){
         System.out.println("Error: "+ ex);
    }    
    initComponents();     // i have long initComponent codes;
}


private void btn_addActionPerformed(java.awt.event.ActionEvent evt) {                                        
    message.setText("");  
    message2.setText("");
    DefaultTableModel model = (DefaultTableModel) itemTable.getModel();
    if(!txt_item.getText().trim().equals("")){
        try{
            String sql = "INSERT INTO items_in_hand (ItemName, Price, Quantity) VALUES (?,?,?)";
            st = con.prepareStatement(sql);
            st.setString(1,txt_item.getText());         
            st.setString(2,txt_price.getText());  
            st.setString(3,txt_quantity.getText());
            st.execute();
            JOptionPane.showMessageDialog(null , "Saved.");
            model.addRow(new Object[] {txt_item.getText(),txt_price.getText(),txt_quantity.getText()});
            message2.setText("Successfully Added.");
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null , ex);
        }  
    }
    else{
        message.setText("The Item name must be provided.");
    }
}                                                               



public static void main(String args[]) {

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ProductTable().setVisible(true);
        }
    });
}

private Connection con;
private PreparedStatement st = null;
private ResultSet rs; 
}    

run: Records from Inventory Database: Error: java.lang.NullPointerException

Can anyone help?

13
  • i tried changing rs = st.executeQuery(query); to rs = st.executeQuery(); still doesnt work. Commented Sep 18, 2014 at 17:10
  • 2
    Hi, please paste the stacktrace. Commented Sep 18, 2014 at 17:11
  • 1
    Please provide an MCVE for better help sooner :) Commented Sep 18, 2014 at 17:12
  • 3
    Have you initialized itemTable? Commented Sep 18, 2014 at 17:14
  • 1
    @DavidConrad thank you for that, i'll do it when i'll be troubleshooting return values. Commented Sep 18, 2014 at 17:44

1 Answer 1

1

When you do new ProductTable().setVisible(true); your constructor is getting called and executed the logic of fetching data from db and

when you do itemTable.setModel(); itemTable is null because you didn't initialize it which I believe you are doing in initComponents(); method which gets called later

Sign up to request clarification or add additional context in comments.

1 Comment

ahh got it. the initComponents() must be called before setModel() so the table is will be initialized. thanks I appreciate your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.