Add CheckBox to jTable?

2019-07-10 21:50发布

问题:

I need to add a checkbox the rows, but I don't know how to do that.

I'm using an own Table Model that I got on internet.

Table Model's code:

import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
/**************/

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

    public ModeloTabela(ArrayList lin, String[] col){
        setLinhas(lin);
        setColunas(col);
    }
    public ArrayList getLinhas(){
        return linhas;

    }
    public void setLinhas(ArrayList dados){
        linhas = dados;
    }
    public String[] getColunas(){
        return colunas;
    }
    public void setColunas(String [] nomes){
        colunas = nomes;
    }
    public int getColumnCount(){
        return colunas.length;
    }
    public int getRowCount(){
        return linhas.size();
    }
    public String getColumnCount (int numCol){
        return colunas[numCol];
    }

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

And this Method will fill the Table:

public void PreencheTabela(String sql, JTable jt1, JTextField j1){
        c.conexao();
        ArrayList dados = new ArrayList();

        String [] Colunas = new String[] {"STATUS", "ID", "FABRICANTE", "FORNECEDOR", "NOME", "CATEGORIA", "DATA DO CADASTRO", " CODIGO DE BARRAS", "QUANTIDADE"};

        c.executaSQL(sql);
        try { 
            c.rs.first();
            do{
            dados.add(new Object[]{c.rs.getInt("prod_id"),c.rs.getString("prod_fabricante"),c.rs.getString("prod_fornecedor"),c.rs.getString("prod_nome"),
                c.rs.getString("prod_categoria"),c.rs.getDate("prod_datacadastro"),c.rs.getString("prod_codbarras"), c.rs.getInt("est_quantidade")});
            j1.setBorder(BorderFactory.createLineBorder(Color.black));
        }while(c.rs.next());

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro!\n"+ex.getMessage());
        }
        ModeloTabela modelo = new ModeloTabela(dados, Colunas);
        jt1.setModel(modelo);
}

Which code can I use? Where do I put this code??

回答1:

you need to implement getColumnClass(int columnIndex) in your TableModel, and make sure it will return Boolean for the column you want to contain checkboxes.

Take a look at this guide, it's very useful: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data