Stworzyłem tabelę i chciałbym, żeby edycyjne pola 2giej kolumny umożliwiały wprowadzenie wyłącznie cyfr. Stworzyłem więc odpowiedni JTextField z walidacją i wetknąłem go do DefaultCellEditora, którym posługuje się moja tabela ... no i wszystko działa z mechanicznego punktu widzenia, ale wizualnie leży. Podczas edycji nie widać całej wpisywanej czcionki. Standardowo bez prywatnego Editora wszystko widać, a przecież to też są JTextFieldy. Poniżej kod:
//JTextField tworzący własny Document
class ValidateTextField extends JTextField
{
private static final long serialVersionUID = 1L;
public ValidateTextField(String defaultValue)
{
super(defaultValue);
}
protected Document createDefaultModel()
{
return new ValidateDocument(validationNumber);
}
}
//Document z walidacją
class ValidateDocument extends PlainDocument
{
private static final long serialVersionUID = 1L;
public void insertString(int pos, String str, AttributeSet a) throws BadLocationException
{
if(string == null) return;
if(isValid(str))
super.insertString(pos, string, a);
}
public boolean isValid(String str)
{
String regularExpression = "^[0-9]+$";
Pattern pattern = Pattern.compile(regularExpression);
Matcher matcher = pattern.matcher(str.trim());
if (!matcher.matches())
return false;
else
return true;
}
}
//Model tabeli
class TableModel extends DefaultTableModel
{
private static final long serialVersionUID = 1L;
public TableModel(int rowCount, int columnCount)
{
setColumnCount(2);
setRowCount(rowCount);
}
public Object getValueAt(int rowIndex, int columnIndex)
{
if(columnIndex == 0)
return rowIndex + 1;
else
return super.getValueAt(rowIndex, columnIndex);
}
public boolean isCellEditable(int row, int col)
{
return col == 1 ? true : false;
}
public String getColumnName(int column)
{
String columnName[] = {"Kolumna 1", "Kolumna 2")};
return columnName[column];
}
}
A tu fragment kodu odpowiedzialnego za utworzenie tabeli:
TableModel tableModel = ;
JTable table = new JTable( new TableModel(rowcount, columnCount) );
table.setCellSelectionEnabled(true);
DefaultCellEditor validateCellEditor = new DefaultCellEditor(new ValidateTextField("0"));
validateCellEditor.setClickCountToStart(0);
TableColumnModel columnModel = table.getColumnModel();
TableColumn col = columnModel.getColumn(1);
col.setCellEditor(validateCellEditor); //wystarczy usunąć tą linię i wszystko działa poprawnie wizualnie, tyle, że bez walidacji
Co w takim razie zrobić, żeby podczas wpisywania wszystko było wizualnie takie samo jak bez podmiany JTextFielda ?