我试图弄清楚如何在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
的行?
答案 0 :(得分:9)
如果您使用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