Java如何向JTable中添加或移除行?

3

我希望你能够帮助我解决如何在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);

我该如何添加一行并删除ID为867954的行?

基于编程或基于输入事件?在所有情况下,您都必须处理jtable.getModel() - nachokk
1个回答

10

如果您使用DefaultTableModel,您就可以做到:

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

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

dtm.removeRow(0); //remove first row
dtm.addRow(new Object[]{...});//add row

如果您想根据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

如何根据第一列中的ID删除一行? - Alosyius

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接