Dimitra Micha
Dimitra Micha

Reputation: 2129

Mark the duplicates in a JTable

I have created a JTable with the help of AbstractTableModel. I would like to mark (change the color of the cell) in a this JTable the third column which has the same entry as the second column. For example:

enter image description here

and so, with the help of this post Check duplicate data in jtable before proceeding

I have came to this:

      table.setDefaultRenderer(Object.class, 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);

            TreeSet<Object> set = new TreeSet<Object>();

            for (int i=0; i<model.getRowCount();i++){
                Object obj = model.getValueAt(i,1); //(row, column)
                if(!set.add(obj))
                {
                    c.setBackground(new java.awt.Color(255, 72, 72));
                }
                else{
                    c.setBackground(null);
                }
            }

            return c;
        }
      });

But, although it seems that it correctly checks for each row (due to some printing I have done), nothing is colored. I would like to add, that the JTable that I have created is a JTable that always changes, meaning there are two buttons, for PREVIOUS and NEXTand this table always changes each form - also the number of the columns changes.

If anything more is requested, I would edit my post.

Thank you.

Upvotes: 0

Views: 892

Answers (1)

StanislavL
StanislavL

Reputation: 57381

I would replace the for in the renderer with

if (column==2) {
    Object obj = model.getValueAt(row,column-1); //(row, column)
    if(value.equals(obj)) {
       c.setBackground(new java.awt.Color(255, 72, 72)); //red
    }
    else{
       c.setBackground(null);
    }
}

Upvotes: 2

Related Questions