I have a basic JTable filled with "item number" and the corresponding "color" for that item, and I need to change the color of the cell that contains that name of the color to that actual color, regardless of whether it is selected or not.
This is the code to my JTable:
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);
The layout is temporary. This is what the table looks like:
So, in this table, the cell containing "red" would be red, the cell containing "blue" would be blue and the cell containing "green" would be green. All other cells remain white like they are.
How would I achieve this?
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