简体   繁体   中英

Set background color for particular row of JTable at runtime

I am working with netbeans IDE7.4, I am adding rows to the JTable at run-time and now I want to set background color for a particular row.

Now the problem is that when the value of that row is changed the color of that particular row is not changed and when I scroll up or down the table the changes are applied.

How to refresh the table at run-time? How to set background color of particular row at runtime?

This is renderer class am using for coloring particular row:

public class MyCellRenderer extends javax.swing.table.DefaultTableCellRenderer
    {         
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, java.lang.Object value, boolean isSelected,     boolean hasFocus, int row, int column)
   {
   final java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,        column);

     Object val=table.getValueAt(row, 2);
     String sval=val.toString();
     sval=sval.replaceAll(":","");
     int ival=Integer.parseInt(sval);
  if(ival==0) 
    {  
        cellComponent.setForeground(Color.black);          
        cellComponent.setBackground(Color.red);              

    }      
    else  
    {      
        cellComponent.setBackground(Color.white);      
        cellComponent.setForeground(Color.black);      
    }    
    if (isSelected)
   {
    cellComponent.setForeground(table.getSelectionForeground());                             cellComponent.setBackground(table.getSelectionBackground());
   }


      return cellComponent;

 }


 }

and am assigning to jtable like this :

    newViewTable.setDefaultRenderer(Object.class,new MyCellRenderer());

newViewTable is the name of JTable.

how to set background color of particular row at runtime?

Use a table cell renderer. See How to Use Tables: Using Custom Renderers for details.

At some point, you need to tell the table that the content has changed in some way.

If you're using a TableModel based on AbstractTableModel , you can use the fireTableXxx events, for example fireTableCellUpdate(row, col) . This will inform the JTable that the model has changed and cause it repaint the table...

You may wish to consider using fireTablesRowsUpdated as this will cause the JTable to update the entire row.

If you are using setValueAt on the model to change the value, you will need to call the appropriate event trigger...

Updated with running example

So, based on you MyCellRenderer renderer, I did this example, and it works fine...

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class TestTable {

    public static void main(String[] args) {
        new TestTable();
    }

    public TestTable() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final DefaultTableModel model = new DefaultTableModel(
                        new Object[]{"A", "B", "C"}, 
                        0
                );

                model.addRow(new Object[]{"A", "B", "1"});
                model.addRow(new Object[]{"C", "D", "0"});
                model.addRow(new Object[]{"E", "F", "1"});
                model.addRow(new Object[]{"G", "H", "0"});

                JTable table = new JTable(model);
                table.setDefaultRenderer(Object.class, new MyCellRenderer());

                JButton btn = new JButton("Add");
                btn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        model.addRow(new Object[]{"N", "O", (int)(Math.round(Math.random() * 1))});
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(table));
                frame.add(btn, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MyCellRenderer extends javax.swing.table.DefaultTableCellRenderer {

        public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, java.lang.Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            final java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            Object val = table.getValueAt(row, 2);
            String sval = val.toString();
            sval = sval.replaceAll(":", "");
            int ival = Integer.parseInt(sval);
            if (ival == 0) {
                cellComponent.setForeground(Color.black);
                cellComponent.setBackground(Color.red);

            } else {
                cellComponent.setBackground(Color.white);
                cellComponent.setForeground(Color.black);
            }
            if (isSelected) {
                cellComponent.setForeground(table.getSelectionForeground());
                cellComponent.setBackground(table.getSelectionBackground());
            }

            return cellComponent;

        }

    }

}

The question now is, what are you doing differently??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM