我有3列和可变行的JTable。用户可以编辑任何单元格的值(因为单元格是可选的)并按Enter键。一旦他/她按下“SAVE”,我就会获得每个单元格的值,并将它们组合成一个单独的字符串,每个单元格的值由一个管道(|)分隔。例如(Col1 | Col1 | Col1 | Col2 | Col2 | Col2 |)到目前为止,非常好。
问题是,尽管这种字符串转换方法有效,但当用户更改表中单元格的值时,代码仍会获得JTable单元格的OLD值。到目前为止跟着我?我不知道如何解决这个问题。以下是代码,以防万一。 (我意识到我的StringBuffer是我应该学会离开的东西)
int rowNumber = inventoryData.getModel().getRowCount();
StringBuffer compiledData = new StringBuffer();
Object currentData = null;
for(int i=0;i<rowNumber;i++){
if(inventoryData.getModel().getValueAt(i, 0) != null) currentData = inventoryData.getModel().getValueAt(i, 0).toString();
compiledData.append(currentData.toString()+"|");
if(inventoryData.getModel().getValueAt(i, 1) != null) currentData = inventoryData.getModel().getValueAt(i, 1).toString();
compiledData.append(currentData.toString()+"|");
if(inventoryData.getModel().getValueAt(i, 2) != null) currentData = inventoryData.getModel().getValueAt(i, 2).toString();
compiledData.append(currentData.toString()+"|");
currentData = "";
}
String repPipesRemoved = compiledData.toString().replaceAll("([|])\\1+", "");
StringBuffer tempBuffer = new StringBuffer(repPipesRemoved);
tempBuffer.append("|");
String finalString = tempBuffer.toString();
感谢阅读 - 有任何想法吗?
答案 0 :(得分:2)
您可以试试这个answer:
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);