Rob987 Rob987 -4 years ago 100
Java Question

JTable missing first row

i already searched the whole web but I can't find a solution, so i decided to ask here.

Following problem: I am using those 2 methods to populate a JTable with a DefaultTableModel, the ResultSet shows the right amount of data entries (i already searched it with System.out.println) but the JTable always misses the first row

I am using a method to get a ResultSet like this:

public static JTable DBCFillBTableAuftraege() {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

JTable table = null;

try {
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement( );
rs = stmt.executeQuery("SELECT a.auftrags_nr, k.firma, a.auftragsdatum, a.lieferdatum, a.rechnungsbetrag, k.name, k.strasse, k.plz, k.ort from auftrag a join kunde k on k.kunden_nr = a.kunden_nr ");
while (rs.next()) {
table = new JTable(tableModel(rs));
return table;
}
} catch (SQLException e) {
System.out.println(e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return table;
}


Which then calls this method:

public static DefaultTableModel TableModel(ResultSet rs)
throws SQLException {

ResultSetMetaData metaData = rs.getMetaData();
System.out.println(rs);
// 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
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}


In my main:

TableAuftrag = DBCFillBTableAuftraege();

scpaneBestell.setViewportView(TableAuftrag);


It works fine, it is showing me my column headers and the data, except one problem:

It is always missing the first row and starts with the second one

Answer Source
while (rs.next()) {
    table = new JTable(tableModel(rs));
    return table;
}

You're consuming the first row of the result set here, and then call tableModel(), which consumes the other rows. The while loop is useless. Just do

table = new JTable(tableModel(rs));
return table;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download