Java添加/删除行到JTable? [英] Java add/remove row to JTable?

查看:210
本文介绍了Java添加/删除行到JTable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to figure out how to add and remove rows from a JTabel. I want to remove rows based on the first column which is a unique ID.

我目前正在创建我的表格:

I am currently creating my table like this:

       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

How could i add a new row and delete the row with ID # 867954 ?

推荐答案

如果您使用 DefaultTableModel

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

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

Now you can add and remove rows:

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

如果您想根据ID删除一行,您可以搜索具有该ID的行并将其删除:

If you want to delete a row based on the ID, you can search for row with that ID and remove it then:

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

这篇关于Java添加/删除行到JTable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆