How to change the text color of a column of a JTable

2

I have a form for payment of installments, and this form has a table where I show both the installments paid and those that still had to be paid.

TopopularthisJTable,ImakeaqueryinthedatabaseandIbringthenecessaryinformation.

publicvoidpreencherParcelas(StringSQL){ArrayListdados=newArrayList();String[]colunas=newString[]{"Data Pagamento", "Valor Parcela", "Status Pagamento"};
    conecta.conexao();
    conecta.executaSQL(SQL);
    String status;
    try {
        conecta.rs.first();
        dataVenda = conecta.rs.getString("data_venda");
        idParcelamento = conecta.rs.getInt("id_parcelamento");
        do {

            if (conecta.rs.getInt("status_pagamento") == 0) {
                status = "PAGAMENTO PENDENTE";
            } else {
                status = "PAGAMENTO EFETUADO";
            }

            dados.add(new Object[]{conecta.rs.getString("data_pagamento"), "R$ " + conecta.rs.getString("valor_parcelas"), status});

        } while (conecta.rs.next());
} catch (SQLException ex) {

        JOptionPane.showMessageDialog(rootPane, "ERRO AO LOCALIZAR PARCELAS" + ex);

    }

ModeloTabela modelo = new ModeloTabela(dados, colunas);

    jTableInformaVencimentos.setModel(modelo);
    jTableInformaVencimentos.getColumnModel().getColumn(0).setPreferredWidth(150);
    jTableInformaVencimentos.getColumnModel().getColumn(0).setResizable(false);

    jTableInformaVencimentos.setModel(modelo);
    jTableInformaVencimentos.getColumnModel().getColumn(1).setPreferredWidth(150);
    jTableInformaVencimentos.getColumnModel().getColumn(1).setResizable(false);

    jTableInformaVencimentos.setModel(modelo);
    jTableInformaVencimentos.getColumnModel().getColumn(2).setPreferredWidth(150);
    jTableInformaVencimentos.getColumnModel().getColumn(2).setResizable(false);

    jTableInformaVencimentos.getTableHeader().setReorderingAllowed(false);
    jTableInformaVencimentos.setAutoResizeMode(jTableInformaVencimentos.AUTO_RESIZE_ALL_COLUMNS);
    jTableInformaVencimentos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    conecta.desconecta();

Template used in the Table

    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(){
        //retorna a quantidade de colunas(conta a quantidade e retorna)
        return colunas.length;
    }

    public int getRowCount(){
        //retorna o tamanho do array(quantos letras tem)
        return linhas.size();
    }

    public String getColumnName(int numCol){
        return colunas[numCol];
    }

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

}

I would like when a "

asked by anonymous 27.06.2016 / 20:43

1 answer

3

You need to change how JTable renders the cell on the screen by using the DefaultTableCellRenderer , or create your own renderer. The simplest way is to use the standard class cited:

DefaultTableCellRenderer renderer = new DefaultTableCellRenderer() {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 

        String str = (String) value;
        if ("PAGAMENTO EFETUADO".equals(str)) {
            c.setForeground(Color.RED);
        } else {
            c.setForeground(Color.BLACK);
        }
        return c;
    }
};

Then, apply the renderer to the desired column, if applicable, column 2:

jTableInformaVencimentos.getColumnModel().getColumn(2).setCellRenderer(renderer);

Remembering that this renderer, if applied as default to JTable , will effect the color change for all columns, so I applied only the reported column.

If you'd like to learn more about renderers, you can access the official tutorial oracle .

    
27.06.2016 / 23:33