简体   繁体   中英

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.

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);

你能尝试在编辑器组件上使用inputverifier,即文本字段吗?

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.

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();
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM