[英]Java add/remove row to JTable?
我试图弄清楚如何从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
的行?
如果使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.