【问题标题】:Getting Value of JTable Cells获取 JTable 单元格的值
【发布时间】:2012-08-23 16:04:47
【问题描述】:

我有这个 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();

感谢阅读 - 有什么想法吗?

【问题讨论】:

  • 在编辑单元格时按回车键,否则只会返回旧值..
  • 我们可能需要查看您的TableModel。你如何实现isCellEditable()setValueAt()?发布sscce 会有所帮助。

标签: java swing jtable edit tablecelleditor


【解决方案1】:

你可以试试这个answer:

table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2018-06-26
    相关资源
    最近更新 更多