Allow only integers in a column of JTable

0

Below I have a Jtable template. There is only one column that is editable for number (seconds). How do I validate to accept only integers, and in case the user types something else, except integer, return ZERO?

public class Tabela_Fluxograma extends AbstractTableModel {
private ArrayList linhas = null;
private String[] colunas = null;

public Tabela_Fluxograma (ArrayList lin, String[] col){
    setLinhas(lin);
    setColunas(col);    
}

public ArrayList getLinhas() {
    return linhas;
}

public void setLinhas(ArrayList dados) {
    this.linhas = dados;
}

public String[] getColunas() {
    return colunas;
}

public void setColunas(String[] nome) {
    this.colunas = nome;
}

public int getColumnCount(){
    return colunas.length;
}

public int getRowCount (){
    return linhas.size();
}

public String getColumnName (int numCol){
    return colunas[numCol];
}

public Object getValueAt (int numLin, int numCol){
    Object[] linha = (Object[])getLinhas().get(numLin);
    return linha[numCol];
}

@Override
public boolean isCellEditable(int row, int column) {
return column == 3;
}

@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    Object[] linha = (Object[]) getLinhas().get(rowIndex);
    linha[columnIndex] = aValue;
    //este método é quem notifica a mudança do model na tabela
    fireTableDataChanged();
}
    
asked by anonymous 21.08.2017 / 21:49

3 answers

1

The correct way to restrict this is through the getColumnClass that your TableModel inherits from AbstractTableModel :

public Class<?> getColumnClass(int columnIndex) { 
    return columnIdex == 3 ? Integer.class : super.getColumnClass(columnIndex);
}

In this way, it will not allow any value other than the type Integer in this column to be saved, being necessary or left blank or filled in correctly to allow the cell editing to be completed in this column.

Just to illustrate what will happen, see the gif below:

    
22.08.2017 / 00:21
0

Good morning. As Articuno commented, I had to change not to allow text or to return zero, although its suggestion is very useful. Thanks for the suggestions. Just to conclude I will put the final section of the tablemodel. I pass the value to another method, validates and returns.

@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    Object[] linha = (Object[]) getLinhas().get(rowIndex);
    int valor = validateInt(aValue);
    linha[columnIndex] = valor;
    fireTableDataChanged();
}

private int validateInt(Object numberObj){
    try {
        int number = Integer.parseInt((String) numberObj);
        return number; 
    } catch (Exception e) {
        return 0;
}
}
    
22.08.2017 / 16:21
-1

Using cast of Int you can do this validation:

private int validateInt(float number){
if(number == (int)number)
   return number;
else
   return 0
}
    
21.08.2017 / 21:53