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

Asked

Viewed 1,765 times

3

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

inserir a descrição da imagem aqui

To popular this JTable, I make a query in the database and bring the necessary information.

public void preencherParcelas(String SQL) {
    ArrayList dados = new ArrayList();
    String[] colunas = new String[]{"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();

Model 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’d like to know when a "PAYMENT MADE" that one String stay in preferred red color. How can I do this?

  • String? You mean ne table cell phone?

  • Whatever makes it easier... If it’s just the same String and insert it already with the new color.

  • It’s not the same thing to colorize string and colorize cell. You need to define what you really want so that the answer matches the problem.

  • I want to color the string and insert it in jTable.

  • Only the text.

  • Pay column only or the whole row text?

  • Just the word pay.

  • Add how you’re filling in jtable. If you’re using a model or Renderer, add them to the question as well.

  • It is up in question, I make a select in the database and add in the table.

  • There is no code that shows how jtable is being populated. Add to question how you are populating jtable.

  • Add the getcolumnclass and getvalueat method of your modelotabela class as well.

  • The model I’m wearing is this.

Show 7 more comments

1 answer

3


You need to change the way the JTable render the cell on the screen, and for that, use the class DefaultTableCellRenderer, or create your own Jump. The simplest way is to use the cited default class:

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;
    }
};

And then apply the right column to the desired column, in your case, column 2:

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

Remembering that this Renderer, if applied as default of the JTable, will make the color change for all columns, so I only applied the informed column.

If you want to learn more about renderers, you can access the official tutorial of oracle.

  • 1

    Perfect Guy... Worked exactly as I needed. Thanks for the attention!

  • @Valdecir Disponha :)

Browser other questions tagged

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