gpt4 book ai didi

Java 添加/删除行到 JTable?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:56:44 26 4
gpt4 key购买 nike

我正在尝试了解如何在 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

关于Java 添加/删除行到 JTable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615089/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com