[RESOLVIDO] Alterar a cor de uma linha na JTable

Boa tarde galera,

Fiz um sistema de cadastramento de tarefas, e queria alterar o a cor de uma linha JTable de acordo com as “Prioridades”, achei este método, que aparentemente funcionaria , más está dando erro quando eu faço o “CLASS” receber um valor, alguem pode me ajudar por favor.

Método:

public void CorNaLinha(){

CLASS “TESTE”; //Aqui mostra o erro

    tabelaTarefas.setDefaultRenderer(Object.class, new DefaultTableCellHeaderRenderer() {

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

            JLabel label = (JLabel) super.getTableCellRendererComponent(table, value,
                    isSelected, hasFocus, row, column);

            Color c = Color.WHITE;
            Object texto = table.getValueAt(row, 4);
            if (texto != null && CLASS.equals(texto.toString())) {
                c = Color.red;
                label.setBackground(c);
                tabelaTarefas.setSelectionForeground(Color.GREEN);

            }
            return label;
        }
    });
}

Segue imagem do problema informado pelo netBeans:

Obrigado.

No seu fonte CLASS é final então você não pode atribuir outro valor à ela.

Neste link tem um exemplo de como criar um renderizador personalizado.

1 curtida

Obrigado, vou estudar e tentar implementar na minha jTable

abaixo exemplo bom

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * codigo original: http://pt.stackoverflow.com/questions/4591/como-colorir-linhas-espec%C3%ADficas-de-uma-jtable
 * codigo original: http://stackoverflow.com/questions/5557485/why-does-my-java-custom-cell-renderer-not-show-highlighting-when-the-row-cell-is
 */
package sip.util;

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

/**
 *
 * @author Alessandra
 */
public class ColorirTabelaTramitacao extends DefaultTableCellRenderer {

/**
 * 
 */
private static final long   serialVersionUID    = 1L;
public static final float R = 0.9f;
public static final float G = 0.5f; 
public static final float B = 0.8f;

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
 super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
   //203,216,227
    //Color c = new Color(203,216,227);
    
    Color c = Color.WHITE;
    Object text = table.getValueAt(row, 3);
    Object text2 = table.getValueAt(row, 10);
    if (text != null && "LICENÇA EMITIDA".equals(text.toString())){
        // RGB
        c = new Color(126,195 ,255);
    }
    if(text != null && "DESARQUIVADO".equals(text.toString())){
        c = Color.GREEN;
    }
    if(text != null && "ARQUIVADO".equals(text.toString())){
        c = Color.RED;
    }
    if(text2 != null){
        c = Color.YELLOW;
    }
                   
       setBackground(c);      

       
   if (isSelected){
          //setForeground(Color.BLUE);
          setBackground(table.getSelectionBackground());    
  }
 

  
    return this;
   
    
}

   
}
1 curtida

O uso da classe abaixo, utilizar até a terceira linha de código.

private void defineModelo() {
        tableModel = (DefaultTableModel) tblTramitacao.getModel();

        listModel = tblTramitacao.getSelectionModel();

        tblTramitacao.setDefaultRenderer(Object.class, new ColorirTabelaTramitacao());

        TableRowSorter<TableModel> sorter = new TableRowSorter<>(tblTramitacao.getModel());
        tblTramitacao.setRowSorter(sorter);

        List<RowSorter.SortKey> sortKeys = new ArrayList<>(25);
        //sortKeys.add(new RowSorter.SortKey(0, SortOrder.DESCENDING));
        //sortKeys.add(new RowSorter.SortKey(0, SortOrder.DESCENDING));
        sorter.setSortKeys(sortKeys);


        listModel.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {

                    mostraDetalheTramitacao();
                }
            }
        });
        try {
            MaskFormatter mascaraCpf = new MaskFormatter("###.###.###-##");
            mascaraCpf.setValueContainsLiteralCharacters(false);
            DefaultFormatterFactory formatterCpf = new DefaultFormatterFactory(mascaraCpf);
            //ftfCpf.setFormatterFactory(formatterCpf);

            MaskFormatter mascaraTel = new MaskFormatter("(##)####-####");
            mascaraTel.setValueContainsLiteralCharacters(false);
            DefaultFormatterFactory formatterTel = new DefaultFormatterFactory(mascaraTel);
            //ftfTel.setFormatterFactory(formatterTel);

            DecimalFormat formatoValor = new DecimalFormat("#,###.00");
            NumberFormatter formatterValor = new NumberFormatter(formatoValor);
            formatterValor.setValueClass(Double.class);
            //ftfValorDigitado.setFormatterFactory(new DefaultFormatterFactory(formatterValor));
            //ftfValorTotal.setFormatterFactory(new DefaultFormatterFactory(formatterValor))

            //tblTramitacao.getColumnModel().getColumn(0).setMaxWidth(0);  
            //tblTramitacao.getColumnModel().getColumn(0).setMinWidth(0);  
            //tblTramitacao.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0);  
            //tblTramitacao.getTableHeader().getColumnModel().getColumn(0).setMinWidth(0);  

            //tblTramitacao.getColumnModel().getColumn(0).setPreferredWidth(60);//1
            tblTramitacao.getColumnModel().getColumn(0).setPreferredWidth(50);//1
            tblTramitacao.getColumnModel().getColumn(1).setPreferredWidth(220);//1
            tblTramitacao.getColumnModel().getColumn(2).setPreferredWidth(150);//2
            tblTramitacao.getColumnModel().getColumn(3).setPreferredWidth(190);//3
            tblTramitacao.getColumnModel().getColumn(4).setPreferredWidth(40);//4
            tblTramitacao.getColumnModel().getColumn(5).setPreferredWidth(40);//5
            tblTramitacao.getColumnModel().getColumn(6).setPreferredWidth(40);//6
            tblTramitacao.getColumnModel().getColumn(7).setPreferredWidth(90);//7
            tblTramitacao.getColumnModel().getColumn(8).setPreferredWidth(30);//8
            tblTramitacao.getColumnModel().getColumn(9).setPreferredWidth(60);//9

            tblTramitacao.getColumnModel().getColumn(10).setMaxWidth(0);
            tblTramitacao.getColumnModel().getColumn(10).setMinWidth(0);
            tblTramitacao.getTableHeader().getColumnModel().getColumn(10).setMaxWidth(0);
            tblTramitacao.getTableHeader().getColumnModel().getColumn(10).setMinWidth(0);

        } catch (ParseException ex) {
            Logger.getLogger(TramitacaoFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
1 curtida

Como ficou:

2 curtidas

@jallisson_jallis, cara muito obrigado, consegui entender e aplicar no meu código. esse exemplo me ajudou muito. Valeeeu.

1 curtida