Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JTable update row

Tags:

java

swing

jtable

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 {

    }
}
like image 225
Alosyius Avatar asked Sep 04 '13 15:09

Alosyius


1 Answers

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);
}
like image 117
Khinsu Avatar answered Nov 07 '22 01:11

Khinsu