Changing Swing Jtable Cell Colors

Java JTable change cell color

Say that the cell you would like to render with a different color represents a status (I'll take Rejected and Approved as examples). I'd then implement a method in my table model called getStatus(int row) which returns the status for any given row.

Then, when that is in place, I'd go about creating a cell renderer responsible for rendering the column which the cell belongs to. The cell renderer would be something in the lines of the below code.

public class StatusColumnCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {

//Cells are by default rendered as a JLabel.
JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);

//Get the status for the current row.
CustomTableModel tableModel = (CustomTableModel) table.getModel();
if (tableModel.getStatus(row) == CustomTableModel.APPROVED) {
l.setBackground(Color.GREEN);
} else {
l.setBackground(Color.RED);
}

//Return the JLabel which renders the cell.
return l;

}

Then, when the renderer is in place, simply "apply" the renderer to the table with the following piece of code:

Table.getColumnModel().getColumn(columnIndex).setCellRenderer(new StatusColumnCellRenderer());

With regard to making a cell editable, simply implement the isCellEditable(int rowIndex, int columnIndex) method in your table model. You also need to implement the method
setValueAt(Object value, int rowIndex, int columnIndex) if you would like to keep the value which the user provides (which i assume you do!).

Changing Swing JTable Cell Colors

You need to make sure you reset the renderer to its default background color (and handle row selection):

if (! table.isRowSelected(row))
{
if(row == 2 && column == 2)
c.setBackground(new java.awt.Color(0, 0, 255));
else
c.setBackground(table.getBackground());
}

In the future post a proper SSCCE with your question.

Java Swing: How do you change colors of very cell in a JTable column based on text?

this code permits to change the row's color

    /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.examen.navegacion;

import java.awt.Color;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

/**
*
* @author wilso
*/
public class Fiea {

public static void main(String[] args) {
JFrame frame = new JFrame("FrameDemo");
String[] title = {"Item Number", "Color"};
String[][] listOfValues = {{"1", "red"}, {"2", "blue"}, {"3", "green"}};

JTable new_table = new JTable(listOfValues, title);
JScrollPane table_pane = new JScrollPane(new_table);
table_pane.setBounds(10, 10, 300, 230);
frame.getContentPane().add(table_pane);

new_table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

c.setBackground(getColor(value.toString()));
return c;
}
});
frame.pack();
frame.setVisible(true);
}

private static Color getColor(String color) {
switch (color) {
case "red":
return Color.RED;
default:
return Color.white;
}

}

}

Result is the next

Sample Image

JTable Set Cell Color At Specific Value

when I select the row on the table, and I want method to only set color at specific column

Try with overridden prepareRenderer() method as suggested by @mKorbel.

sample code:

Object[] columnNames = { "A", "B", "C", "D" };
Object[][] data = {
{ "abc", new Double(850.503), 53, true },
{ "lmn", new Double(36.23254), 6, false },
{ "pqr", new Double(8.3), 7, false },
{ "xyz", new Double(246.0943), 23, true } };

JTable table = new JTable(data, columnNames) {
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
Object value = getModel().getValueAt(row, col);
if (getSelectedRow() == row) {
if (value.equals(false)) {
comp.setBackground(Color.red);
} else if (value.equals(true)) {
comp.setBackground(Color.green);
} else {
comp.setBackground(Color.white);
}
} else {
comp.setBackground(Color.white);
}
return comp;
}
};

When selected first row:

Sample Image

When selected second row.

Sample Image

Read more...



EDIT

As per your last comment

Is it possible to change color with out clicking (selecting) row on the table?

Yes just remove the check of selected row.

    Object value = getModel().getValueAt(row, col);
if (value.equals(false)) {
comp.setBackground(Color.red);
} else if (value.equals(true)) {
comp.setBackground(Color.green);
} else {
comp.setBackground(Color.white);
}

Sample Image

Java jTable color row on defined cell change

You're forgetting to set the border and highlighting back to default if the test condition is not true. For example

if (isRowSelected(row)) {
if ("test".equals(type)) {
jc.setBorder(_highlight); // Green color
jc.setBackground(Color.GREEN);
} else {
jc.setBorder(highlight); // Red color
}
} else {
jc.setBorder(null);
jc.setBackground(null);
}

Change background color of one cell in JTable

You'll need a custom renderer to display the green color when a cell is marked modified in your model.

You'll also need a custom editor to set the model's modified state in your implementation of stopCellEditing(), mentioned here.

A related example of a custom renderer and editor is shown here.

Addendum: Here's an example of the approach described.

inage

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;

/**
* @see https://stackoverflow.com/a/12352838/230513
*/
public class ModifiedCells extends JPanel {

public ModifiedCells() {
final MyModel model = new MyModel();
JTable table = new JTable(model);
table.setDefaultRenderer(String.class, new MyRenderer());
table.setDefaultEditor(String.class, new MyEditor(table));
this.add(table);
}

private static class MyRenderer extends DefaultTableCellRenderer {

Color backgroundColor = getBackground();

@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);
MyModel model = (MyModel) table.getModel();
if (model.getState(row)) {
c.setBackground(Color.green.darker());
} else if (!isSelected) {
c.setBackground(backgroundColor);
}
return c;
}
}

private static class MyEditor extends DefaultCellEditor {

private JTable table;
private MyModel model;

public MyEditor(JTable table) {
super(new JTextField());
this.table = table;
this.model = (MyModel) table.getModel();
}

@Override
public boolean stopCellEditing() {
model.setState(table.getEditingRow(), true);
return super.stopCellEditing();
}
}

private static class MyModel extends AbstractTableModel {

private final List<Row> list = new ArrayList<Row>();

public MyModel() {
list.add(new Row("One", true));
list.add(new Row("Two", false));
list.add(new Row("Three", false));
}

public boolean getState(int row) {
return list.get(row).state.booleanValue();
}

public void setState(int row, boolean state) {
list.get(row).state = state;
}

@Override
public int getRowCount() {
return list.size();
}

@Override
public int getColumnCount() {
return 1;
}

@Override
public Object getValueAt(int row, int col) {
return list.get(row).name;
}

@Override
public void setValueAt(Object aValue, int row, int col) {
list.get(row).name = (String) aValue;
fireTableCellUpdated(row, col);
}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}

private static class Row {

private String name;
private Boolean state;

public Row(String name, Boolean state) {
this.name = name;
this.state = state;
}
}
}

private void display() {
JFrame f = new JFrame("ModifiedCells");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
new ModifiedCells().display();
}
});
}
}


Related Topics



Leave a reply



Submit