Java向JTable添加/删除行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18615089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java add/remove row to JTable?
提问by Alosyius
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.
我想弄清楚如何从 JTabel 添加和删除行。我想根据作为唯一 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
?
如何添加新行并删除 ID 为 # 的行867954
?
采纳答案by Jimmy T.
You can do it if you use DefaultTableModel
:
如果你使用,你可以做到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:
如果要根据 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