我曾经在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);
}
我的AbstractTableModel:
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;
}
}
最佳答案
以下是使用AbstractTableModel
的示例:
public class CustomTableModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private static final String[] columnNames = new String[]{"ID", "Name", "Number", "Yes/No"};
protected List<Foo> lstFoo;
protected Class<?>[] types = new Class[]{Integer.class, String.class, String.class, Boolean.class};
public CustomTableModel(List<Foo> lstFoo)
{
this.lstFoo = lstFoo;
fireTableDataChanged();
}
@Override
public String getColumnName(int columnIndex)
{
return columnNames[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
return types[columnIndex];
}
@Override
public boolean isCellEditable(int row, int columnIndex)
{
return false;
}
@Override
public Object getValueAt(int row, int column)
{
if(row < 0 || row >= lstFoo.size()) return null;
Foo obj = lstFoo.get(row);
switch(column)
{
case 0: return obj.getId();
case 1: return obj.getName();
case 2: return obj.getNumber();
case 3: return obj.isYes();
default: return null;
}
}
@Override
public int getRowCount()
{
return lstFoo.size();
}
@Override
public int getColumnCount()
{
return columnNames.length;
}
}
关于java - 将AbstractTableModel实现到JTable。如何添加方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10559020/