我想用 JTable
绑定(bind) mysql 表内容。我连接成功了。我将表格行和宽度设置为 500。它将显示 500 行,包括数据和空行。现在我只想查看数据。我不想查看空行。
请帮帮我
我的应用程序在插入方法 getRowCountFromDB()
后变慢了..
class AbstractTableEmployee extends AbstractTableModel {
int row2;
private String[] columnNames = { "ID", "Name", "Company", "Department", "Location", "Mobile NO" , "Shift" };
private Object[][] data = new Object[500][500];
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
int row = 0;
try {
row = this.count();
} catch (SQLException ex) {
Logger.getLogger(AbstractTableEmployee.class.getName()).log(Level.SEVERE, null, ex);
}
return row;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
private int getRowCountFromDB() throws SQLException {
Connection con = (Connection) DBConnection.getDBConnection();
int row = 0;
Statement st = null;
ResultSet rs = null;
String Sql = "Select * from Employee_Master where status = 'Active'";
try {
st = (Statement) con.createStatement();
rs = st.executeQuery(Sql);
while (rs.next())
{
row++;
}
}
finally {
con.close();
rs.close();
st.close();
}
return row;
}
private int count() throws SQLException {
return this.getRowCountFromDB();
}
}
提前致谢。
最佳答案
JTable
的文档以下示例说明如何使用具有自定义表格模型的表格。
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return 10; }
public int getRowCount() { return 10;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
};
JTable table = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(table);
这是您必须提供的最小实现。
编辑:
参见 3.3.4.8 Counting Rows在 MySQL Reference 中获取有关如何有效获取行计数的信息。在我看来,当您想要的只是一个数字时,您正在获取整个表格。
你会想要类似的东西
Select COUNT(*) from Employee_Master where status = 'Active'
然后只读取该值。
至于您的数据
,我看不出它有 500 列的理由,因为您的表似乎只有 7 列。
无论如何,根据表的大小,您可能不希望一次将所有数据都放入其中。如果是这种情况,您始终可以根据用户在 JTable
中滚动的位置获取和缓存行 block 。你可以使用 LIMIT为此。
对于其他一些想法和技巧,您还应该看看这个 question其中涵盖了类似的问题。
关于Java-如何在 JTable 上动态初始化行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8501206/