问题
Unlike most data structures, JTable does not have isEmpty() method. So how can we know if a given JTable doesn't contain any value?
回答1:
This will return actual number of rows, irrespective of any filters on table.
int count= jTable.getModel().getRowCount();
jTable.getRowCount() will return only visible row count. So to check isEmpty() then it's better to use getRowCount() on model.
public static boolean isEmpty(JTable jTable) {
if (jTable != null && jTable.getModel() != null) {
return jTable.getModel().getRowCount()<=0?true:false;
}
return false;
}
回答2:
table.getRowCount();
table.getColumnCount();
If either one is 0, then there is no data.
回答3:
you have a fixed number of columns .. suppose three
public int Actualrows(DefaultTableModel m) {
int row = 0;
int i = 0;
for (i = 0; i < m.getRowCount(); ++i) {
try {
if (!(m.getValueAt(i, 0).equals("")) && !(m.getValueAt(i, 1).equals(""))
&& !(m.getValueAt(i, 2).equals(""))) {
row++;
}
} catch (NullPointerException e) {
continue;
}
}
return row;
}
if the return value equal 0 its absolutely an empty table
回答4:
Actually, there is no method for learning it my friend. But myself, using a method to learn whether it's empty or not.
At first, while you create JTable set the default row count 0. When you want to use JTable, make the JTable with data which return count from the database. So if there is no data.getRowCount() will return 0 again. And so, you will know whether JTable is empty or not.
try (ResultSet rs = st.executeQuery(query)) {
int colcount = rs.getMetaData().getColumnCount();//get's the row count in the database
DefaultTableModel tm = new DefaultTableModel();
for (int i = 1; i <= colcount; i++) {
tm.addColumn(rs.getMetaData().getColumnName(i));
}
while (rs.next()) {
Object[] row = new Object[colcount];
for (int i = 1; i <= colcount; i++) {
row[i - 1] = rs.getObject(i);
}
tm.addRow(row);
}
jTblAd.setModel(tm);
conn.close();
}
Lastly i want to say that if the jTable has head,for example : Name-Surname-Age etc, table.getRowCount(); table.getColumnCount();not working because of head of jtable. So,my opinion is that if we cant check the jTable,check the Dataset which be written in the table.
来源:https://stackoverflow.com/questions/30603531/how-to-know-if-a-jtable-is-empty