My application throws NullPointerException. I created connection between MySQL database and my second class.
I can’t call DefaultTableModel by method in my second class.
How can I solve this problem?
public class MySQL extends javax.swing.JFrame {
private DefaultTableModel modelTabeli;
public MySQL(){
initComponents();
BazaDana bd = new BazaDana();
try{
modelTabeli = bd.map();
jTable1.setModel(modelTabeli);
}
catch(Exception e){
System.out.println(e.toString());
}
}
public static void main(String args[]) throws Exception{
BazaDana bd = new BazaDana();
bd.readDataBase();
}
}
Second class
import java.sql.*;
import javax.swing.table.DefaultTableModel;
public class BazaDana{
public DefaultTableModel map() throws SQLException
{
defaultTableModel = new DefaultTableModel();
int numberOfColumns = resultSetMetaData.getColumnCount();
while (resultSet.next())
{
Object [] rowData = new Object[numberOfColumns];
for (int i = 0; i < rowData.length; ++i)
{
rowData[i] = resultSet.getObject(i+1);
}
defaultTableModel.addRow(rowData);
}
return defaultTableModel;
}
}
Ok, may I give you an alternative solution if your goal is to separate GUI class from class which queries database. Don’t return DefaultTableModel, return just values from ResultSet through some collection, like this:
Create MySql GUI class:
Then create Java bean class:
And finally your BazaDana class which queries database: