Andez
Andez

Reputation: 5848

Prevent Java Swing JTable losing focus when invalid data entered

We currently have a focus problem with a JTable/JTextEditor in java swing. The JTable has a custom cell editor which is a JTextField.

The issue is when a cell is being edited and contains invalid data, and the user clicks on a JButton, the text field will stop editing and the JButton actionPerformed (clicked) is called. The JTable#setValueAt handles validation so if the data in the JTextField is invalid, the underlying TableModel is not updated.

Ideally, we do not want to let the JButton click occur. Focus should remain with the JTable or the JTextField.

Clicking the button will perform a submit action and close the frame the table is in. As the validation in the TableModel#setValueAt does not update the value, it submits the old value.

Can this be done? I am still fairly new to Swing so I am not aware what to check.

Unfortunately, our code is not straight forward. The UI is constructed from XML in such a way that the button knows nothing about anything else on a form (this is code I have inherited).

In .net you could stop a control losing focus by handling a Validating event and setting a cancel flag. Is there a similar mechanism with Java.

Upvotes: 1

Views: 2858

Answers (4)

Peter
Peter

Reputation: 5798

I'd achieved a similar functionality by overriding the stopCellEditing method in my JTable's CellEditor.

@Override
public boolean stopCellEditing() {
   String s = (String) getCellEditorValue();       
   if (s != null) {           
       if (!testYourValue()) {           
           Toolkit.getDefaultToolkit().beep();           
           return false;
       }
   }
   return super.stopCellEditing();
} 

Upvotes: 0

trashgod
trashgod

Reputation: 205785

Validating the input after editing has concluded, in setValueAt(), may be inconveniently late. The editor itself can preclude navigation for invalid values, as shown in this example that links to the corresponding tutorial section.

For valid values, you can make the table commit when losing focus:

table.putClientProperty("terminateEditOnFocusLost", true);

Upvotes: 4

rlinden
rlinden

Reputation: 2041

When the focus is lost from a component, the lost focus method is called (more reference in http://docs.oracle.com/javase/tutorial/uiswing/events/focuslistener.html). Therefore, you may call the validation method when you lose the focus.

If you do not need to be aware of the specific field being edited, you can also perform validation inside your button and prevent the submission if it is not sucessful.

Upvotes: 0

DKumar
DKumar

Reputation: 352

Can you try using inputverifier on the editor component, i.e. text field?

Upvotes: 0

Related Questions