Manuel Sacramento
Manuel Sacramento

Reputation: 13

Java jtable non editable

I'm developing a project and I have a little problem that does not find a solution.

I have a jtable who writes the results to a database and I am not able to block the editing of cells.

I have the following code to pass the query:

BaseDados Ligacao = new BaseDados();
LigaBD = Ligacao.LigaBD();
String consulta="SELECT modalidade_id AS 'ID', modalidade_nome AS 'Nome' FROM modalidades";
resultado = Ligacao.ResultadoConsulta(LigaBD, consulta);
jTableListaMod.setModel(Tabelas.CriaModeloTabela(resultado));

And the next class to make the table model:

import com.mysql.jdbc.ResultSetMetaData;
import java.sql.ResultSet;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class Tabelas {
    public static TableModel CriaModeloTabela (ResultSet resultado)  {
        try {
            ResultSetMetaData metaData = (ResultSetMetaData) resultado.getMetaData();
            int NumeroColunas= metaData.getColumnCount();
            Vector NomesColunas = new Vector();
            for (int coluna = 0; coluna < NumeroColunas; coluna++){
                NomesColunas.add(metaData.getColumnLabel(coluna+1));
            }
            Vector Linhas= new Vector();
            while(resultado.next()){
                Vector Linha = new Vector();
                for (int i = 1; i <= NumeroColunas; i++){
                    Linha.add(resultado.getObject(i));
                }
                Linhas.add(Linha);
            }
            resultado.first();
            return new DefaultTableModel(Linhas, NomesColunas);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

I've tried things like this:

public class NonEditableModel extends DefaultTableModel {

    NonEditableModel(Object[][] data, String[] columnNames) {
        super(data, columnNames);
    }

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

Appreciate all the help.

Upvotes: 1

Views: 103

Answers (1)

camickr
camickr

Reputation: 324118

return new DefaultTableModel(Linhas, NomesColunas);

You want to use your custom TableModel:

return new NonEditableModel(Linhas, NomesColunas);

Also, variable names should NOT start with an upper case character. Some of your names are correct, other are not. Be consistent!!!

Upvotes: 4

Related Questions