Reputation: 997
I have been trying to get data from my Derby database and populate a jTable created by the Netbeans GUI builder.
I have an account class where the following code is kept:
public static DefaultTableModel buildTableModel() throws SQLException {
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
Vector columns = new Vector();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String stmt = "SELECT * FROM APP.DATAVAULT";
ps = Main.getPreparedStatement(stmt);
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
} finally {
try {
ps.close();
} catch (Exception e) {
}
try {
rs.close();
} catch (Exception e) {
}
}
DefaultTableModel tableModel = new DefaultTableModel(data, columns);
return tableModel;
}
As you can see it returns a DefaultTableModel with two parameters, data and columns.
Then, within my GUI class I have the following:
My field:
Account acc = new Account();
Constructor:
public SPPMainGUI() throws SQLException {
initComponents();
datavaultjTable.setModel(acc.buildTableModel());
}
My main method:
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
new SPPMainGUI().setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(SPPMainGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
The code is set to populate my jTable with ALL data from the datavault table, no matter what user is logged in.
I have data in my datavault table:
And this is what my jTable looks like when I run my program and log in successfully:
This is what it SHOULD look like, but populated:
Where am I going wrong in my code? I've been stumped on this for 2 weeks now.
Upvotes: 3
Views: 5100
Reputation: 159754
You need to add your columnNames
to your columns
header data, otherwise nothing will appear in your JTable
:
for (int column = 1; column <= columnCount; column++) {
...
}
columns.add(columnNames); <--- add this line
Rather than have a redundant variable for this data, you could simply use columnNames
for your model instead:
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
Upvotes: 2