Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JTable - change row background color

807606Apr 13 2007 — edited Apr 13 2007
I have the following code:
import java.awt.Color;
import java.awt.Component;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

class ColoredTableCellRenderer
    extends DefaultTableCellRenderer
{
    public Component getTableCellRendererComponent
        (JTable table, Object value, boolean selected, boolean focused, int row, int column)
    {
        setEnabled(table == null || table.isEnabled()); // see question above

        if ((row % 2) == 0)
            setBackground(Color.green);
        else
            setBackground(Color.lightGray);

        super.getTableCellRendererComponent(table, value, selected, focused, row, column);

        return this;
    }
}
And
		//JTable
		String[] head = {"Namn", "M�ndag", "Tisdag", "Onsdag", "Torsdag", "Fredag"};
		String[][] data = {{"Niklas", "9-15", "9-15", "9-15", "9-15","9-15"}, 
							{"Niklas", "9-15", "9-15", "9-15", "9-15","9-15"}}; 
		JTable table = new JTable(data, head);
		JScrollPane centerFrame = new JScrollPane(table);
		//table.setEnabled(false);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		
		TableColumnModel tcm = table.getColumnModel();
		TableColumn tm = tcm.getColumn(0);
		tm.setCellRenderer(new ColoredTableCellRenderer());
I want the possibility to change background color to one row, column or cell, but as i have read on the net and taken code from the above code should change the color per row. And thats correct, but it changes the code only for the one column!
I want to change the entire row or column!

Plz help!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 11 2007
Added on Apr 13 2007
5 comments
16,394 views