Java添加/删除行到JTable?

Alo*_*ius 3 java swing jtable defaulttablemodel

我试图弄清楚如何从JTabel添加和删除行.我想根据第一列删除行,这是一个唯一的ID.

我目前正在创建这样的表:

       String[] colName = new String[] {
           "ID#", "Country", "Name", "Page titel", "Page URL", "Time"
       };
       Object[][] products = new Object[][] {
           {
               "867954", "USA", "Todd", "Start", "http://www.url.com", "00:04:13"
           }, {
               "522532", "USA", "Bob", "Start", "http://www.url.com", "00:04:29"
           }, {
               "4213532", "USA", "Bill", "Start", "http://www.url.com", "00:04:25"
           }, {
               "5135132", "USA", "Mary", "Start", "http://www.url.com", "00:06:23"
           }
       };


       table = new JTable(products, colName);
Run Code Online (Sandbox Code Playgroud)

我怎么能添加一个新行并删除ID为#的行867954

Jim*_* T. 9

你可以这样做,如果你使用DefaultTableModel:

DefaultTableModel dtm = new DefaultTableModel(products, colName);
table = new JTable(dtm);
Run Code Online (Sandbox Code Playgroud)

现在您可以添加和删除行:

dtm.removeRow(0); //remove first row
dtm.addRow(new Object[]{...});//add row
Run Code Online (Sandbox Code Playgroud)

如果要根据ID删除行,可以搜索具有该ID的行并将其删除,然后:

String searchedId = "867954";//ID of the product to remove from the table
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(searchedId))
    {
        row = i;
        break;
    }

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

else
    ...//not found
Run Code Online (Sandbox Code Playgroud)