Is it possible to change the color of a jtable cell of type Boolean?

Asked

Viewed 102 times

-1

I am trying to change the background color of certain Jtable cells, but when I change the color of a Boolean column it loses the format of a Checkbox and appears written "true" or "false". I want to know if it is possible to change the background of Boolean columns without losing the Checkbox format.

Code I’m using to change cell color:

import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class ColorCellRenderer extends DefaultTableCellRenderer {

private final Color par = new Color(255, 255, 255);
private final Color impar = new Color(242, 242, 242);
private final Color color;
private final int[] rows;

public ColorCellRenderer(Color color, int[] rows) {
    super();
    this.color = color;
    this.rows = rows;
}

@Override
public Component getTableCellRendererComponent(JTable table,
        Object value,
        boolean isSelected,
        boolean hasFocus,
        int row,
        int column) {

    if (row%2 != 0) {
        this.setBackground(impar);
    } else {
        this.setBackground(par);
    }

    if(this.color != null && this.rows != null){
        for (int i=0 ; i<this.rows.length ; i++) {
            int rowToPaint = this.rows[i];
            if(rowToPaint == row){
                this.setBackground(this.color);
            }
        }
    }else if(this.color != null){
        this.setBackground( this.color );
}
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

}
public void validate() {
}
public void revalidate() {
}
}

To use the above class:

int[]rows = {0,1,4};
jTable1.getColumnModel().getColumn(0).setCellRenderer(new ColorCellRenderer(Color.blue,rows));
jTable1.getColumnModel().getColumn(1).setCellRenderer(new ColorCellRenderer(Color.yellow,rows));
jTable1.getColumnModel().getColumn(2).setCellRenderer(new ColorCellRenderer(Color.pink,rows));
jScrollPane1.setViewportView(jTable1);

Test code with table:

import java.awt.Color;

public class NewJFrame2 extends javax.swing.JFrame {

public NewJFrame2() {
    initComponents();
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setLayout(null);

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"123", "qwe", "asd",  new Boolean(false)},
            {"456", "ert", "dfg",  new Boolean(true)},
            {"879", "uio", "jkl",  new Boolean(true)},
            {"0-=", "p[", "ç]",  new Boolean(false)},
            {"zxc", "cvb", "nbm",  new Boolean(true)}
        },
        new String [] {
            "Title 1", "Title 2", "Title 3", "Title 4"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }
    });
    int[]rows = {0,1,4};
    jTable1.getColumnModel().getColumn(0).setCellRenderer(new ColorCellRenderer(Color.blue,rows));
    jTable1.getColumnModel().getColumn(1).setCellRenderer(new ColorCellRenderer(Color.yellow,rows));
    jTable1.getColumnModel().getColumn(2).setCellRenderer(new ColorCellRenderer(Color.pink,rows));
    jScrollPane1.setViewportView(jTable1);

    jPanel1.add(jScrollPane1);
    jScrollPane1.setBounds(10, 11, 375, 275);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
    );

    pack();
}// </editor-fold>                        

public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame2().setVisible(true);
        }
    });
}
             
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;           
}

Example of what Jtable looks like:

Cor nas células determinadas

If I add the line jTable1.getColumnModel().getColumn(3).setCellRenderer(new ColorCellRenderer(Color.orange,rows)); Jtable shows up like this: Cor nas células determinadas porém sem o formato de CheckBox na coluna 3

1 answer

0


In the class rewriting the method getTableCellRendererComponent it is necessary to create a Jcheckbox instead of returning the class itself, as the class creates a Jlabel for the cells. Therefore it is necessary to replace the return of the method that created.

if (Boolean.class.equals(table.getModel().getColumnClass(column))){
        JCheckBox cb = new JCheckBox();
        cb.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        //Alinha o check box para ficar no centro da coluna e não à esquerda
        if(isSelected) //Se a linha está selecionada
            cb.setBackground(table.getSelectionBackground());
            //Background igual ao backgroud de seleção da própria tabela
        else
            cb.setBackground(this.getBackground());
            //Recebe o background definido
        cb.setSelected((Boolean)value);
        //Indica se o check box vai estar marcado ou não, de acordo com o valor da célula
        cb.setOpaque(true);//Para que o background apareça é necessário deixar opaco
        return cb;//Retorna o JCheckBox criado
    }
    else
        return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

In the if is checked if the class of the column is of type Boolean, if it is created a new Jcheckbox to return, instead of returning the super of one’s own class.

The table looks like this:

Tabela com background correto

Browser other questions tagged

You are not signed in. Login or sign up in order to post.