Share on Google+Share on Google+

Set Different Color to different row in Java Program

Advertisement
In this section, you will learn how to set different color to table row using java swing.

Java Set Different Color to different row

In this section, you will learn how to set different color to table row using java swing.For this purpose, we have created a table and use TableCellRenderer class to change the color of cell. This class provides the method setBackground() which allow us to set different color to different row.

Here is the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;

public class TableRow extends JFrame {
	JPanel panel = new JPanel();

	public TableRow() {
		JTable table = new JTable(new DefaultTableModel(new Object[][] {
				{ "A", "Delhi", "111111" }, { "B", "Agra", "222222" },
				{ "C", "Mumbai", "333333" }, { "D", "Chennai", "444444" },
				{ "E", "Baroda", "555555" }, { "F", "Kolkata", "666666" } },
				new Object[] { "Name", "Address", "Phone No" }));
		ChangeColor renderer = new ChangeColor("Name");

		for (int i = 0; i < table.getColumnCount(); i++)
			table.getColumn(table.getColumnName(i)).setCellRenderer(renderer);
		JScrollPane scroll = new JScrollPane(table);
		panel.add(scroll);
		this.setContentPane(panel);
		this.setBounds(100, 50, 500, 180);
	}

	public static void main(String arg[]) {
		TableRow tes = new TableRow();
		tes.setVisible(true);
		tes.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}

class ChangeColor extends JLabel implements TableCellRenderer {
	private String columnName;

	public ChangeColor(String column) {
		this.columnName = column;
		setOpaque(true);
	}

	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean selected, boolean hasFocus, int row, int column) {
		Object columnValue = table.getValueAt(row, table.getColumnModel()
				.getColumnIndex(columnName));
		if (value != null)
			setText(value.toString());
		setBackground(table.getBackground());
		setForeground(table.getForeground());

		if (columnValue.equals("A"))
			setBackground(Color.green);
		if (columnValue.equals("B"))
			setBackground(Color.red);
		if (columnValue.equals("C"))
			setBackground(Color.blue);
		if (columnValue.equals("D"))
			setBackground(Color.pink);
		if (columnValue.equals("E"))
			setBackground(Color.orange);
		if (columnValue.equals("F"))
			setBackground(Color.yellow);
		return this;
	}
}



Advertisements

Posted on: November 2, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.