Java JTable update row

岁酱吖の 提交于 2020-01-13 16:25:09

问题


I am creating a JTable like this:

           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);

How could i update the row by ID? i want to update the whole row where the ID equals 55.

Edit: I know how to detele by row ID but how do i actually update the cells?

  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:


You can use DefaultTableModel#setValueAt(java.lang.Object, int, int)

or

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

Edit:

Example:

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);
}


来源:https://stackoverflow.com/questions/18618436/java-jtable-update-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!