Reputation: 35
I'm starting to learn how to use databases and was trying to export the data from my h2 database into a JTable. The table comes up with the correct number of rows, however, only the first row is filled with data. The rest is a blank grid. I posted some code below for the JTable. If someone needs to see more code, I'll post it.
public class Table extends JTable{
public static int rows;
public static String[][] data;
public static String[] columns = {"Author", "Customer", "Date"};
public static void populateTable() throws ClassNotFoundException, SQLException{
//Server is name of the database class
Server server = new Server();
Statement stat = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stat.executeQuery("SELECT * FROM data");
rs.last();
rows = rs.getRow();
rs.beforeFirst();
data = new String[3][rows];
while(rs.next()){
int i = 0;
data[0][i] = rs.getString("Author");
data[1][i] = rs.getString("Customer");
data[2][i] = rs.getString("Date");
System.out.println(rs.getString("Author"));
i = i++;
}
rs.close();
}
}
class MyTableModel extends DefaultTableModel{
String[] columnNames = {"Author", "Customer", "Date"};
MyTableModel() throws ClassNotFoundException, SQLException{
addColumn(columnNames[0]);
addColumn(columnNames[1]);
addColumn(columnNames[2]);
}
@Override
public int getRowCount() {
return rows;
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[columnIndex][rowIndex];
}
I'm also able to print to the console all the data, but it just won't show up in the JTable. I have been stuck on this problem for hours but I don't know what I'm doing wrong. Thanks in advance
Upvotes: 1
Views: 41
Reputation: 159854
This statement is a no-op since i
is assigned before it is incremented
i = i++;
just use
i++;
Also initialize i
before entering the loop
Upvotes: 3
Reputation: 35096
You should either use a for loop or declare i outside of your loop. As it stands, you are setting all data to row 0 (int i = 0);
while(rs.next()){
int i = 0; // this will run for every row
data[0][i] = rs.getString("Author");
data[1][i] = rs.getString("Customer");
data[2][i] = rs.getString("Date");
System.out.println(rs.getString("Author"));
i = i++;
}
Upvotes: 2