Java add/remove row to JTable?

好久不见. 提交于 2019-11-30 19:34:14

问题


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

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


回答1:


You can do it if you use 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

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


来源:https://stackoverflow.com/questions/18615089/java-add-remove-row-to-jtable

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