java - 获取 JTable 单元格的值(value)

标签 java swing jtable edit tablecelleditor

我有一个包含 3 列和可变行的 JTable。用户可以编辑任何单元格的值(因为单元格是可选择的)并按下回车键。一旦她/他按下“保存”,我就会得到每个单元格的值,并将它们组合成一个字符串,每个单元格的值由竖线 (|) 分隔。例如 ( Col1|Col1|Col1|Col2|Col2|Col2| ) 到目前为止一切顺利。

问题是,尽管这种字符串转换方法有效,但是当用户更改表中单元格的值时,代码仍然获取 JTable 单元格的旧值。跟我走这么远?我不确定如何解决这个问题。这是下面的代码,以防万一。 (我意识到我的 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();

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

最佳答案

你可以试试这个answer :

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

关于java - 获取 JTable 单元格的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12065244/

相关文章:

java - 为什么主题消息不会出队?

java - 使用 Maven 程序集插件创建包含胖 jar (jar-with-dependencies) 的 ZIP 文件

Java AWT drawImage 竞争条件 - 如何使用同步来避免它

java - 在 JPanel 上绘制近距离 GPS 坐标

java - JTable,通过鼠标点击在具体单元格中动态添加标签

java - 垃圾收集器何时何地开始发挥作用?

java - 尝试使用 actionListener 将字符串颠倒过来

JAVA UI ActionListener 2次连续点击带有if else语句的按钮

java - 表示 Color 对象时为 JTable 中的单个单元格着色

java - 无法使用新数据刷新我的 JTable