JTable 在未提交时从单元格获取值

JTable get value from cell when is not submitted

我想在未提交单元格(单元格处于编辑模式)时从单元格中获取值 - "real time";可能吗?

我试过了,但只有当我提交数据时它才有效 - 按 enter

int row = jTable.getSelectedRow();
int col = jTable.getSelectedColumn();
String cellValue = jTable.getValueAt(row, col).toString();

我想在不退出的情况下获取按键单元格值,在键入时实时获取此文本

KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
          @Override
          public boolean dispatchKeyEvent(KeyEvent e) {

              int row = jTable.getSelectedRow();
              int col = jTable.getSelectedColumn();


              if (e.getID() == KeyEvent.KEY_RELEASED) {
                  if (jTable.isEditing())
                      jTable.getCellEditor().stopCellEditing();
                  String cellValue = (jTable.getValueAt(row, col)!=null) ? jTable.getValueAt(row, col).toString() : "";
                  System.out.println(cellValue);
              }}

jTable.getCellEditor().stopCellEditing() - 打字时导致难看的 in/out 动画

@camickr 很抱歉造成您的困惑。你的解决方案没问题。 我只需要添加 jTable.editCellAt(row, col);返回编辑模式。

再次感谢

cell is in edit mode

在将值保存到模型之前必须停止编辑。

最简单的方法是使用:

JTable table = new JTable(...);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

当您创建 table.

现在,当您单击按钮进行处理时,table 失去焦点,因此数据被保存。

查看 Table Stop Editing 了解更多信息。