Java add/remove row to JTable?

后端 未结 1 693
刺人心
刺人心 2021-01-06 13:49

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

1条回答
  •  梦毁少年i
    2021-01-06 14:18

    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

    0 讨论(0)
提交回复
热议问题