Java JTable 更新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18618436/
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 JTable update row
提问by Alosyius
I am creating a JTable like this:
我正在创建一个这样的 JTable:
String[] colName = new String[] {
"ID#", "Country", "Name", "Page titel", "Page URL", "Time"
};
Object[][] products = new Object[][] {
{
"123", "USA", "Bill", "Start", "http://www.url.com", "00:04:23"
},
{
"55", "USA", "Bill", "Start", "http://www.url.com", "00:04:23"
}
};
dtm = new DefaultTableModel(products, colName);
table = new JTable(dtm);
How could i update the row by ID? i want to update the whole row where the ID equals 55.
如何通过 ID 更新行?我想更新 ID 等于 55 的整行。
Edit: I know how to detele by row ID but how do i actually update the cells?
编辑:我知道如何按行 ID 删除,但我如何实际更新单元格?
public void removeVisitorFromTable(String visitorID) {
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(visitorID)) {
row = i;
break;
}
if(row != -1) {
dtm.removeRow(row);//remove row
} else {
}
}
采纳答案by Khinsu
You can use DefaultTableModel#setValueAt(java.lang.Object, int, int)
您可以使用DefaultTableModel#setValueAt(java.lang.Object, int, int)
or
或者
DefaultTableModel#setDataVector(java.util.Vector, java.util.Vector)
DefaultTableModel#setDataVector(java.util.Vector, java.util.Vector)
Edit:
编辑:
Example:
例子:
private void updateRow(String visitorID, String[] data) {
if (data.length > 5)
throw new IllegalArgumentException("data[] is to long");
for (int i = 0; i < dtm.getRowCount(); i++)
if (dtm.getValueAt(i, 0).equals(visitorID))
for (int j = 1; j < data.length+1; j++)
dtm.setValueAt(data[j-1], i, j);
}