i am trying to retrieve data from a database and display then on a table in java. Below is the code sample, can someone tell me whats wrong wiz it because when an running it i am getting the following error:
java.lang.NullPointerException.
package sample;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import net.proteanit.sql.DbUtils;
public class Table extends JFrame{
JTable table;
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
private void UpdateJTable(){
String sql = "select firstname, status from tblmember";
try{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
private void conect(){
conn = myconnection.ConnectDb();
}
public Table(){
setLayout(new FlowLayout());
String [] columnName={"Name", "Status"};
Object [][] data={
{null, null},
{null, null}
};
table = new JTable(data, columnName);
table.setPreferredScrollableViewportSize(new Dimension(500,50));
table.setFillsViewportHeight(true);
JScrollPane sp = new JScrollPane(table);
add(sp);
}
public static void main(String[] args){
Table gui = new Table();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(700, 500);
gui.setVisible(true);
gui.setTitle("AAAAAAAA");
gui.UpdateJTable();
gui.conect();
}
}
Try inverting the order of these two lines:
to
connis null when you try and update.