I have a custom cell editor which validates if the entered value is a number and its length is 3.
Right now I am able to make sure that if invalid value is entered the current cell stays editable and focus does not move to next cell.
But when valid value is entered the current cell still remains editable and the focus alone shifts to next cell.
Also The commented part of showing an alert also doesnt work. The whole application hangs and i believe the prompt is coming in the background.
Below is the code of the editor
public class DepartmentCellEditor extends DefaultCellEditor{
public DepartmentCellEditor()
{
super( new JTextField() );
}
public boolean stopCellEditing()
{
JTable table = (JTable)getComponent().getParent();
try
{
boolean isValid = true;
String s = getCellEditorValue().toString();
if ( s.length() == 3 ) {
for ( int i = 0; i < s.length(); i++ ) {
if ( !Character.isDigit( s.charAt( i ) ) ) {
isValid = false;
break;
}
}
} else {
isValid = false;
}
if ( !isValid ) {
JTextField textField = (JTextField)getComponent();
textField.setBorder(new LineBorder(Color.red));
textField.selectAll();
textField.requestFocusInWindow();
/*JOptionPane.showMessageDialog(
null,
"Please enter a 3 digit number.",
"Alert!",JOptionPane.ERROR_MESSAGE);*/
} else {
JTextField textField = (JTextField)getComponent();
textField.setBorder(new LineBorder(Color.black));
}
return isValid;
}
catch(ClassCastException exception)
{
JTextField textField = (JTextField)getComponent();
textField.setBorder(new LineBorder(Color.red));
textField.selectAll();
textField.requestFocusInWindow();
return false;
}
}
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column)
{
Component c = super.getTableCellEditorComponent(
table, value, isSelected, row, column);
((JComponent)c).setBorder(new LineBorder(Color.black));
return c;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…