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

我通过覆盖JTableCellEditorstopCellEditing方法来实现类似的功能。

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

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

链接地址: http://www.djcxy.com/p/52440.html

上一篇: 线库生成失败,链接器错误

下一篇: 防止Java Swing JTable在输入无效数据时失去焦点