13

I have a JTable as follow.

alt text

So, while the JTable is still in editing mode (There is a keyboard cursor blinking at Dividend column), clicking OK directly will not commit the data into table model. Clicking OK merely close the dialog box.

I need to press ENTER explicitly, in order to commit the data into table model.

While JTable is still in editing mode, before closing dialog box, is there any way I can tell the JTable by saying, "Hey, is time for you to commit the changes into your model"

The source code for this dialog box is as follow Dialog Box Source Code. Do look at jButton1ActionPerformed for the executed code when OK is pressed.

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • You probably used an IDE to generate the GUI code. But could you please change the variable names to something more friendly. Very hard to read when everythign is labeled button1 button2 label1 – Sean Oct 07 '10 at 16:59
  • Sorry about that. Do look at jButton1ActionPerformed for the executed code when OK is pressed. – Cheok Yan Cheng Oct 07 '10 at 17:03

3 Answers3

16

I'm not sure if it will work (it would have been nice to have a SCCE), but try this:

TableCellEditor editor = table.getCellEditor();
if (editor != null) {
  editor.stopCellEditing();
}
Guillaume
  • 14,306
  • 3
  • 43
  • 40
6

Table Stop Editing gives a couple of approaches.

EDIT

Example from article:

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

Example from article:

if (table.isEditing())
    table.getCellEditor().stopCellEditing();
Jonathan
  • 949
  • 1
  • 11
  • 13
camickr
  • 321,443
  • 19
  • 166
  • 288
5

To make the whole stable stop editing completely in any state (editing or not), you can call editing stopped:

    table.editingStopped(new ChangeEvent(table));

That way you don't have to check for editors/state/etc.

John Gardner
  • 24,225
  • 5
  • 58
  • 76
  • https://docs.oracle.com/javase/8/docs/api/javax/swing/JTable.html#editingStopped-javax.swing.event.ChangeEvent- I really wanted this to be the right answer because it is simple and elegant, however according to the documentation this method is intended for use internally by JTable. Technically there are no guarantees that it will accessible or work the same way in future versions. That being said, I don't see the Java Swing libraries getting any major updates anytime soon, so while it's not technically safe, I imagine it's still a practical solution. – Jonathan Jun 04 '19 at 17:09