Error when trying to put JCheckBox in a JTable column

0

I'm trying to add a column to a DefaultTableModel , but it seems to be giving some problems. Follow the code!

JCheckBox jcheck;
DefaultTableModel modelo = new DefaultTableModel(null, new String[]{"Data", "Hora", "SAP", "BPCS", "Etiqueta", "Min", "Max", "MV", "Min", "Max", "T5", "Min", "Max", "TS2", "Min", "Max", "T90", "Min", "Max", "Densidade", "C-Chart", "Blooming","Aprovar"}) {
    @Override
    public boolean isCellEditable(int row, int col) {
        return true;
    }
};

jcheck = new JCheckBox();
TableColumn coluna_um = jTable1.getColumnModel().getColumn(22);
coluna_um.setCellEditor(new DefaultCellEditor(jcheck));

Could anyone of a force?

    
asked by anonymous 14.11.2017 / 12:29

1 answer

1

JCheckBox is a component that can be considered "Boolean", that is, is either marked, or is not. Because it has only two states, when you define a column of this type in DefaultTableModel , the renderer itself uses this component as a representation of a Boolean column , and its only job is to define which column should be of this type. See the example below:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class JTableCheckboxTest extends JFrame{

    public void createAndShowGUI() {

        Object[][] rowData = {null, null, null};
        Object[] columnNames = { "Currency Column ", "Column Two",};

        DefaultTableModel model = new DefaultTableModel(rowData, columnNames){
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                return columnIndex == 0 ? Boolean.class : super.getColumnClass(columnIndex);
            }
        };

        JTable table = new JTable(model);       

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
        setPreferredSize(new Dimension(300, 150));
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String args[]) throws IllegalAccessException {
        EventQueue.invokeLater(() -> new JTableCheckboxTest().createAndShowGUI());
    }
}

Notice that in the getColumnClass() method I check to see if the column index is 0, when it does, the column will be a Boolean type, which will make it a Checkboxes column:

One point of your code is that, by default, all columns of a DefaultTableModel are editable, so overwriting the isCellEditable() method to return true is redundant.

    
14.11.2017 / 12:53