有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ArrayList更新了插入一行,但Jtable仍然没有刷新

我必须创建一个java swing应用程序,允许用户浏览一些Oracle表

我以这种方式实现了JTable:

public class TableModel extends AbstractTableModel{
        .
        .
        .

  public List <List <String> > result = null;     
        .
        .
        .
  public void createTable(ResultSet r) throws SQLException {
    rs = r;
    numcols = getColumnCount();
    result = new ArrayList();
    while (rs.next()) {
      List <String> row = new ArrayList<>(numcols);
      for (int i=1; i<= numcols; i++)
          row.add(rs.getString(i).replace("00:00:00.0", "")); //just managing stuffs .. nothing important. Don't care of this replace.
      result.add(row);
     }
     fireTableStructureChanged();
   }

  public void addRow(){ 
    List <String> row = new ArrayList<>();
    for(int i=1;i<=getColumnCount();i++)
        row.add("");
    result.add(row);
    fireTableStructureChanged();
  }

  public Object getValueAt(int row, int col) {
    return result.get(row).get(col);
  }

  public int getColumnCount() {
  if (rs == null) {
     return 0;
  }
  try {
     return rs.getMetaData().getColumnCount();
  } catch (SQLException e) {
     System.err.println("error in colcount");
     return 0;
  }
 }

  public int getRowCount() {
  int totalRows = 0;
  try {
    rs.last();
    totalRows = rs.getRow();
    rs.beforeFirst();
  } catch(Exception ex)  {
        return 0;
  }
    return totalRows ;
  }
}

因此,我将数据库数据存储到arraylist中,然后使用arraylist打印表。 现在,在addRow()函数中,我向arraylist添加了一条空记录(在我看来,空记录是由所有null(“”)字符串组成的记录)。 最后,使用fireTableStructureChanged()方法,我希望表能够自我刷新。。但这永远不会发生,我不明白为什么

我已经检查过新行是否已成功加载到arraylist中: 我将数据库表中存储的所有数据都保存到arraylist中,新行成功加载到arraylist中。 所以我发誓问题在于fireTableStructureChanged()方法

谢谢:3


共 (1) 个答案

  1. # 1 楼答案

    我找到了解决办法。 那太尴尬了

    @tsolakp你帮了我很多

    因为在使用ArrayList之前,我直接处理ResultSet,所以忘记了更新getrowcount。 因此,由于插入在arraylist上只是“客户端”,所以显示的行只有“n”(其中n是数据库上的行数)。所以我永远不会显示我的新行,因为它没有加载到数据库中

    仅此而已:)

    也许努力编码会让这些错误隐形:X