My goal is to display data from a database using JTable.
Referencing code from: Most simple code to populate JTable from ResultSet
I modified the code to suit my situation. I have a class TopicData with the following method:
public DefaultTableModel buildTableModel(){
//open connection
ResultSet rs = null;
Vector<String> columnNames = new Vector<String>();
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
int columnCount = 0;
DBController db = new DBController();
db.setUp("myDatabase");
String dbQuery = "SELECT topicName, topicDate, topicCategory, topicUser FROM topicTable ORDER BY topicDate";
rs = db.readRequest(dbQuery);
try{
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
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);
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//close connection
db.terminate();
return new DefaultTableModel(data, columnNames);
}
And in another class TopicView:
private JTable getTable() {
if (table == null) {
TopicData topic= new TopicData();
table = new JTable(topic.buildTableModel());
table.setShowGrid(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setBounds(95, 59, 625, 357);
}
return table;
}
I realized that my table does not have headers at the top of each column. https://i.stack.imgur.com/FcnHb.png
So I simplified my TopicData to troubleshoot:
public DefaultTableModel testTableModel(){
Vector<String> columnNames = new Vector<String>();
columnNames.add("test1");
columnNames.add("test1");
columnNames.add("test1");
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
Vector<Object>vector = new Vector<Object>();
vector.add("test2");
vector.add("test2");
vector.add("test2");
data.add(vector);
return new DefaultTableModel(data, columnNames);
}
Once again, the table does not have headers. The word "test1" does not appear anywhere on the table, while there are 3 columns of "test2" displayed.
I'm really puzzled by this, any help would be appreciated.