在我的代码中,我有一些JTextFields和一个单独的JTable,具有多个列和行。我想验证表中的特定单元格,如果它无效,则不允许用户将光标移动到另一个字段。如果用户将光标移动到表中的其他单元格(不同的行或列),我的代码可以正常工作,但是如果我将光标移动到窗体上的其他字段,光标就会移动。我已经验证了我的 stopCellEditing 函数被调用并返回 false。当边框无效时,我将边框变为红色。这是正常工作的,正如预期的那样,只是光标在移动。这是我的代码。
用于受影响列的单元格编辑器使用
// Set up the verifier to make sure the user has entered a valid value
statusTable.getColumn(statusTable.getColumnName(1)).
setCellEditor(new CellEditor(new SvidVerifier(), this));
我的扩展 DefaultCellEditor 是
class CellEditor extends DefaultCellEditor {
InputVerifier verifier = null;
ModView view = null;
public CellEditor(InputVerifier verifier, ModView view) {
super(new JTextField());
this.verifier = verifier;
this.view = view;
}
@Override
public boolean stopCellEditing() {
if (KeyboardFocusManager.getCurrentKeyboardFocusManager().
getFocusOwner() == view.publicBrowseButton) {
super.cancelCellEditing();
return true;
}
boolean canStop = verifier.verify(editorComponent) &&
super.stopCellEditing();
return canStop;
}
}
我的验证器是
class IdVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
JTextField tf = (JTextField) input;
try {
if ((Integer.parseInt(tf.getText()) >= 1) &&
(Integer.parseInt(tf.getText()) <= 32)) {
tf.setBorder(new LineBorder(
UIManager.getColor("activeCaptionBorder")));
return true;
} else {
tf.setBorder(new LineBorder(Color.RED));
return false;
}
} catch (Exception ex) {
tf.setBorder(new LineBorder(Color.RED));
return false;
}
}
}
谢谢你的帮助。
在我看来,表格被告知停止编辑,但仅此而已。CellEditor 界面没有提到 stopCellEdit 的焦点处理。
您可能必须将焦点侦听器绑定到窗体上的其他组件,并在该侦听器中验证以前的焦点是否在表上。如果是这样,并且表格仍在编辑,请将焦点设置回表格。
使用@camickr指出的文章,我能够成功地完成我需要的事情,并通过使用 TextField.requestFocusInWindow()
函数解决我的问题。