Colorize jTable lines ready

Asked

Viewed 422 times

0

I have a code and I need to make some improvements, but I’m not able to insert them properly, I’m a beginner and I have some difficulties.

The software has:

  • a Beansclient class with the get and set;
  • a Beanstable class; Abstracttablemodel constructor of the type arrays
  • a method to fill the type table String sql

I am not able to enter the condition to color the lines. Anyone can help?

Murillo, as requested follows the information:

//jTable model

public void preencherTabela(String Sql) {
        ArrayList dados = new ArrayList();
        String [] colunas = new String []{"Matricula","Ativo","Nome","Data Matric.","Data Vencimento","Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"};
        conex.conexao();
        conex.executaSql(Sql);
        try {
            conex.rs.first();            
            do{
               dados.add(new Object[]{conex.rs.getInt("id_cd"),conex.rs.getString("ativo_cd"),conex.rs.getString("nome_cd"),conex.rs.getString("dtmat_cd"),conex.rs.getString("dtvenc_cd"),conex.rs.getString("jan_cd"),conex.rs.getString("fev_cd"),conex.rs.getString("mar_cd"),conex.rs.getString("mai_cd"),conex.rs.getString("jun_cd"),conex.rs.getString("jul_cd"),conex.rs.getString("ago_cd"),conex.rs.getString("set_cd"),conex.rs.getString("out_cd"),conex.rs.getString("nov_cd"),conex.rs.getString("dez_cd")}); 
            }while(conex.rs.next()); 
        }catch(SQLException ex){
            JOptionPane.showMessageDialog(rootPane,"Erro ao preencher arraylist"+ex);
        }
        BeansTabela modelo = new BeansTabela(dados, colunas);

        jTableCadCliente.setModel(modelo);
        jTableCadCliente.getColumnModel().getColumn(0).setPreferredWidth(65);
        jTableCadCliente.getColumnModel().getColumn(0).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(1).setPreferredWidth(50);
        jTableCadCliente.getColumnModel().getColumn(1).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(2).setPreferredWidth(170);
        jTableCadCliente.getColumnModel().getColumn(2).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(3).setPreferredWidth(100);
        jTableCadCliente.getColumnModel().getColumn(3).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(4).setPreferredWidth(100);
        jTableCadCliente.getColumnModel().getColumn(4).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(5).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(5).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(6).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(6).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(7).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(7).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(8).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(8).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(9).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(9).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(10).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(10).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(11).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(11).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(12).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(12).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(13).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(13).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(14).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(14).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(15).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(15).setResizable(true);
        jTableCadCliente.getColumnModel().getColumn(16).setPreferredWidth(60);
        jTableCadCliente.getColumnModel().getColumn(16).setResizable(true);
        jTableCadCliente.getTableHeader().setReorderingAllowed(false);
        jTableCadCliente.setAutoResizeMode(jTableCadCliente.AUTO_RESIZE_OFF);
        jTableCadCliente.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //jTableCadCliente.setBackground(Color.ORANGE); //


        conex.desconecta();
    }

 //abaixo o metodo de seleção:

public BeansCliente filtro(BeansCliente mod) {
        conex.conexao();
        conex.executaSql("select *from clientesmilfe where nome_cd like'%"+mod.getPesquisa()+"%'");
        try {
            conex.rs.first();
            mod.setId(conex.rs.getInt("id_cd"));
            mod.setAtivo(conex.rs.getString("ativo_cd"));
            mod.setNome(conex.rs.getString("nome_cd"));
            mod.setDataMatricula(conex.rs.getString("dtmat_cd"));
            mod.setDataVencimento(conex.rs.getString("dtvenc_cd"));
            mod.setJaneiro(conex.rs.getString("jan_cd"));
            mod.setFevereiro(conex.rs.getString("fev_cd"));
            mod.setMarco(conex.rs.getString("mar_cd"));
            mod.setAbril(conex.rs.getString("abr_cd"));
            mod.setMaio(conex.rs.getString("mai_cd"));
            mod.setJunho(conex.rs.getString("jun_cd"));
            mod.setJulho(conex.rs.getString("jul_cd"));
            mod.setAgosto(conex.rs.getString("ago_cd"));
            mod.setSetembro(conex.rs.getString("set_cd"));
            mod.setOutubro(conex.rs.getString("out_cd"));
            mod.setNovembro(conex.rs.getString("nov_cd"));
            mod.setDezembro(conex.rs.getString("dez_cd"));
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Cliente não cadastrado!");
        }
        conex.desconecta();
        return mod;
    } 

Follow the additional information

jTable:

package modeloBeans;

import java.awt.Component;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author anild
 */
public class BeansTabela extends AbstractTableModel{

    //arrayslist é uma coleção que pode armazenar qualquer tipo de objeto
    //ela é um vetor do tipo string
    private ArrayList linhas= null;
    private String[] colunas= null;
//abaixo vamos criar o metodo 
public BeansTabela(ArrayList lin, String[] col) {
    setLinhas(lin);
    setColunas(col);
}    

    public BeansTabela() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    BeansTabela(String profissional_1, int i, String contador, double d) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    BeansTabela(BeansTabela tabc) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    /**
     * @return the linhas
     */
    public ArrayList getLinhas() {
        return linhas;
    }

    /**
     * @param linhas the linhas to set
     */
    public void setLinhas(ArrayList linhas) {
        this.linhas = linhas;
    }

    /**
     * @return the colunas
     */
    public String[] getColunas() {
        return colunas;
    }

    /**
     * @param colunas the colunas to set
     */
    public void setColunas(String[] colunas) {
        this.colunas = colunas;
    }
    //DAQUI PARA BAIXO É PARA EVITAR ERROS NOS METODOS CRIADOS ACIMA
    @Override
    public int getColumnCount() {
        return colunas.length;
    }

    @Override
    public int getRowCount() {
        return linhas. size();
    }
    /**
    *o metodo e o parametro int numCol é para pegar o nome da coluna
     * @param numCol
     * @return 
    */
    @Override
    public String getColumnName(int numCol){
        return colunas[numCol];
    }

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

}

Condition is the late due date;

  • 1

    Please add a [mcve] of your jtable with some sample data for testing and what kind of condition the line would be colored.

  • This code you added doesn’t help much to understand the problem nor to come up with a solution. It’s not just a [mcve]. You also don’t say which condition should color the line.

  • The diegofm, explain to me what is to you a ""a minimal, complete and verifiable example"", because the weibe understood and responded helping, now you are scrutinizing this and does not help dude, what your, what you want, the complete code, is what is an example for you, how the other managed to help and you there in all your wisdom is writing the same thing and does not help at all

  • Verifiable is that it can be easily reproduced, that is you have to create a simplified version of your code so that we can reproduce the problem just by copying the code and putting to run, the link that Diego put http://answall.com/help/mcve. already explains this ;)

  • that was the code after ready: Color c = Color.GREEN; Object text = table.getValueAt(Row, 1); if (text != null && "SIM".equals(text.toString())) c = Color.RED; comp.setBackground(c); the important thing for me here, is to learn, status not.

  • Hello, to conclude the topic you must accept a reply, take a look here more on the subject: http://meta.pt.stackoverflow.com/a/1079/3117

Show 1 more comment

1 answer

1


to color the line you must create a Defaulttablecellrenderer.

DefaultTableCellRenderer tableCellRenderer = new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
             Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
             comp.setForeground(Color.WHITE);
             comp.setBackground(Color.BLACK);
             return comp;
        }
    };
jTableCadCliente.setDefaultRenderer(Object.class, tableCellRenderer);
  • Thank you Weibe, that was a simple and objective answer, very good..

  • Weibe the example you passed worked perfectly, I’m creating the condition, in which case it is ( take the value of column 1 and if the value is a string "" it returns a color other than another) on top of this model I sent like this:

  • Inside the template you sent I implemented the condition, but not certain: Object ref = table.getValueAt(column, 1); if (column = "YES"){ comp.setFont(new Font("Arial", Font.PLAIN, 12)); comp.setForeground(Color.red); }Else{ comp.setFont(new Font("Arial", Font.PLAIN, 12)); comp.setForeground(Color.black); }

  • The correct is Object ref = table.getValueAt(Row, 1); this way you will catch column 1 of each row of your table.

  • I will correct and test

  • Color c = Color.GREEN; Object text = table.getValueAt(Row, 1); if (text != null && "SIM".equals(text.toString())) c = Color.RED; comp.setBackground(c); It worked, it was worth your help!!

Show 1 more comment

Browser other questions tagged

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