我曾经在 JTable 中显示我的数据库数据,它工作正常。我发现我需要实现 AbstractTableModel 或 DefaultTableModel 来立即更新数据。
我不确定我应该在 getValueAt() 中写什么?我应该在哪里添加 fireDataChanged()?任何指导表示赞赏,谢谢!
我曾经使用以下代码检索我的数据库数据:
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/watchlist","root","root");
String sql = "SELECT * FROM watchlist";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i));
}
int rowCount = md.getColumnCount();
while (rs.next())
{
Vector row = new Vector(rowCount);
for (int i=1; i <= rowCount; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
我的抽象表模型:
public class MyTableModel extends AbstractTableModel
{
Vector columnNames = new Vector();
Vector data = new Vector();
public void connectionDB()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/watchlist","root","root");
String sql = "SELECT * FROM watchlist";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
}
catch(Exception e)
{
System.out.println(e);
}
}
public int getColumnCount()
{
return columnNames.size();
}
public int getRowCount()
{
return data.size();
}
public Object getValueAt()
{
return data;
}
public boolean isCellEditable(int row, int col)
{
return false;
}
}