Hy ,

I have a table , in which i am adding new rows , after 6 rows with data I want to add a empty row with the background color red then another 6 rows with white background

private void populate(){
         
         DefaultTableModel model = (DefaultTableModel) table.getModel();
         int i,j;
         for(j=0;j<6;j++){

            for(i=0;i<6;i++){
                model.addRow(new Object[]{"dada","dadaddd"});
            }
            
            model.addRow(new Object[]{"",""});
         }
         
        
    
    }

How can i change the color of the empty row?

Recommended Answers

All 11 Replies

Hy ,
I read a little bit more , and here it is what i have done :

public class tabel extends javax.swing.JFrame {
    DefaultTableModel tableModel;
    int itsRow=0;int itsColumn=0;
    private Vector<Vector<String>> data;
    private Vector<Vector<String>> da;
    private Vector<String> header;
    /** Creates new form tabel */
    public tabel() {
        
        DefaultTableModel tableModel;
        Vector<Vector<String>> tabelVector = new Vector<Vector<String>>();
        Vector<String> tabel = new Vector<String>();
        header();
        data = tabelVector;
        tableModel = new DefaultTableModel(data,header);        
        //table = new JTable(tableModel);  
        initComponents();
        
        table.setModel(tableModel);
        table.setDefaultRenderer(Color.class, new ColorRenderer(true));
        populate();
        
        //pack();
    }
    
    private void header(){
        header = new Vector<String>();
        header.add("da");
        header.add("daa");
    
    }
    
    @SuppressWarnings("unchecked")                       
  
    private void populate() {
         
         DefaultTableModel model = (DefaultTableModel) table.getModel();
         
         int i,j;
         for(j=0;j<6;j++){
            for(i=0;i<6;i++){
                model.addRow(new Object[]{"dada","dadaddd"});
                
            }
            model.addRow(new Object[]{"",Color.red}); //(cells i want red)
            model.addRow(new Object[]{"             Camera:409A",Color.red}); //(cells i want red)
            
        }
    }
  
    // Paint current color
   
    public static void main(String args[]) {
       
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try{new tabel().setVisible(true);
                }catch(Exception e){}
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration                   
}

And here it is the ColoRenderer class :

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import java.awt.Color;
import java.awt.Component;

public class ColorRenderer extends JLabel
                           implements TableCellRenderer {
    Border unselectedBorder = null;
    Border selectedBorder = null;
    boolean isBordered = true;

    public ColorRenderer(boolean isBordered) {
        this.isBordered = isBordered;
        setOpaque(true); //MUST do this for background to show up.
    }

    public Component getTableCellRendererComponent(
                            JTable table, Object color,
                            boolean isSelected, boolean hasFocus,
                            int row, int column) {
        Color newColor = (Color)color;
        setBackground(newColor);
        if (isBordered) {
            if (isSelected) {
                if (selectedBorder == null) {
                    selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
                                              table.getSelectionBackground());
                }
                setBorder(selectedBorder);
            } else {
                if (unselectedBorder == null) {
                    unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
                                              table.getBackground());
                }
                setBorder(unselectedBorder);
            }
        }
        
        setToolTipText("RGB value: " + newColor.getRed() + ", "
                                     + newColor.getGreen() + ", "
                                     + newColor.getBlue());
        return this;
    }
}

However in the table it swows me :

java.awt.Color[r=255,g=0,b=0]

Was that a question?
You create row containing a Color.RED as its value and it's displayed as "java.awt.Color[r=255,g=0,b=0]", which is exactly what you would expect since the default renderer calls toString() on the value Object.
To achieve the result you described in your first post I would expect to see some piece of code in the getTableCellRendererComponent method that tests the row number and sets the background color according to the row number.

I don`t know what else too do and what piece of code should i post here

n the first parameter for setDefaultRenderer, put the class literal for the Class that you want to override rendering. I.e., if your data consist all of strings, you can put

myTable.setDefaultRenderer(String.class, new CustomRenderer());

If your data also consists of values with BigDecimal or Integer as classes, you have to invoke that method several times for each class type (BigDecimal.class or Integer.class in each case).

And finally, to change the background color you do this in your renderer:

class CustomRenderer extends DefaultTableCellRenderer 
{
    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);
        c.setBackground(new java.awt.Color(255, 72, 72));
        return c;
    }
}

1. Thank you for helping me.But it still does not work


This is my code now , it still prints me java.awt.Color[r=255,g=72,b=72]

public class tabel extends javax.swing.JFrame {
    DefaultTableModel tableModel;
    int itsRow=0;int itsColumn=0;
    private Vector<Vector<String>> data;
    private Vector<Vector<String>> da;
    private Vector<String> header;
    /** Creates new form tabel */
    public tabel() {
        
        DefaultTableModel tableModel;
        Vector<Vector<String>> tabelVector = new Vector<Vector<String>>();
        Vector<String> tabel = new Vector<String>();
        header();
        tabelVector.add(tabel);
        data = tabelVector;
        tableModel = new DefaultTableModel(data,header);        
        initComponents();       
        table.setModel(tableModel);      
        table.setDefaultRenderer(String.class, new CustomRenderer());
        populate();
    }
    
    private void header(){
        header = new Vector<String>();
        header.add("da");
        header.add("daa");
    
    }
    
    @SuppressWarnings("unchecked")
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        table.setName("table"); // NOI18N
        jScrollPane1.setViewportView(table);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 842, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(60, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(36, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

   
   private void populate(){

         DefaultTableModel model = (DefaultTableModel) table.getModel();

         int i,j;
         for(j=0;j<6;j++){
            for(i=0;i<6;i++){
                model.addRow(new Object[]{"dada","dadaddd"});

            }
            model.addRow(new Object[]{"",new java.awt.Color(255, 72, 72)});

        }

   }
   class CustomRenderer extends DefaultTableCellRenderer 
{
    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);
        c.setBackground(new java.awt.Color(255, 72, 72));
        return c;
    }
}
    public static void main(String args[]) {
        

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try{new tabel().setVisible(true);
                }catch(Exception e){}
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
}

only other thing i can say is try

Color.RED

instead of

new java.awt.Color(255,72,72)

you may need to add

import java.awt.color;

I changed it and added java.awt.Color , no result.

Is it because i`m using DefaultTableModel?

This is my code now , it still prints me java.awt.Color[r=255,g=72,b=72]

I already explained this - did you read my earlier post?

You create row containing a Color.RED as its value and it's displayed as "java.awt.Color[r=255,g=0,b=0]", which is exactly what you would expect since the default renderer calls toString() on the value Object.

model.addRow(new Object[]{"",new java.awt.Color(255, 72, 72)});

Thanks for replay , but i solved it a few hours ago.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.