Java JTable更新行

时间:2013-09-04 15:51:13

标签: java swing jtable

我正在创建一个像这样的JTable:

           String[] colName = new String[] {
               "ID#", "Country", "Name", "Page titel", "Page URL", "Time"
           };
           Object[][] products = new Object[][] {
               {
                   "123", "USA", "Bill", "Start", "http://www.url.com", "00:04:23"
               },

               {
                   "55", "USA", "Bill", "Start", "http://www.url.com", "00:04:23"
               }

           };

           dtm = new DefaultTableModel(products, colName);
           table = new JTable(dtm);

我如何按ID更新行?我想更新ID等于55的整行。

编辑:我知道如何通过行ID来检测,但我如何实际更新单元格呢?

  public void removeVisitorFromTable(String visitorID) {
    int row = -1; //index of row or -1 if not found

    //search for the row based on the ID in the first column
    for(int i=0;i<dtm.getRowCount();++i)
        if(dtm.getValueAt(i, 0).equals(visitorID)) {
            row = i;
            break;
        }

    if(row != -1) {
        dtm.removeRow(row);//remove row
    } else {

    }
}

1 个答案:

答案 0 :(得分:5)

您可以使用DefaultTableModel#setValueAt(java.lang.Object, int, int)

DefaultTableModel#setDataVector(java.util.Vector, java.util.Vector)

修改

示例:

private void updateRow(String visitorID, String[] data) {
    if (data.length > 5)
        throw new IllegalArgumentException("data[] is to long");
    for (int i = 0; i < dtm.getRowCount(); i++)
        if (dtm.getValueAt(i, 0).equals(visitorID))
            for (int j = 1; j < data.length+1; j++)
                dtm.setValueAt(data[j-1], i, j);
}