Change Background Color of One Cell in Jtable

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();
}
});
}
}

Dynamically change the background color of a JTable cell

//This is the code which I have used to change jtable cell background color dynamically
[green color indicates empty(free) cell and red color indicates occupied cells][1]
int row, col, row1, column;
TableCellRenderer renderer;
private static final int STATUS_COL = 1;
String host = "jdbc:mysql://localhost/your_database";
String username = "root";
String password = "";
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(host, username, password);
stmt = connect.createStatement();
String sql = "your query";
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData meta = rs.getMetaData();
Object[][] data = new Object[10][2];
DefaultTableModel model = new DefaultTableModel(data, col);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
rs = stmt.executeQuery(sql);
int rowCnt = 0;
try{

rs = stmt.executeQuery(sql);
if(rs.last()){
rowCnt = rs.getRow();
}
} catch (Exception e){
System.out.println("Error getting row count");
e.printStackTrace();
}

int nCol = rs.getMetaData().getColumnCount();
List<String[]> table = new ArrayList<>();
String[] row = new String[nCol];
for(int l=1; l<rowCnt; l++)
{
for (int iCol = 1; iCol <= nCol; iCol++) {
Object obj = rs.getObject(iCol);
row[iCol - 1] = (obj == null) ? null : obj.toString();
jTable1.setDefaultRenderer(Object.class, new EntryCellRender());
}
table.add(row);
}
} catch (Exception e) {
System.out.println(e);
}
}
public class EntryCellRender extends DefaultTableCellRenderer {

private final Color alt2 = Color.RED;
private final Color alt1 = Color.GREEN;
private final Color invalidStatus = Color.RED;

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component cr = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if ("".equals(table.getValueAt(row, col))) {
setBackground(alt1);
} else {
setBackground(alt2);
}

return cr;
}

private Color colorAlternator(int row) {
if ((row % 2) == 0) {
return alt1;
} else {
return alt2;
}
}
}

enter code here

[1]: https://i.stack.imgur.com/Fi4LF.png

jTable Cell background color

First of all variable names should NOT start with an upper case character. Some of your variables are correct, others are not. Be consistent!!!

I've tried to color a cell of a jTable using the renderers, but they are useless they lag the table and make it impossible to see.

Just because you don't understand the concept does not make it useless. The problem is with your code, not the concept of renderers.

Your posted code makes no sense. You can't set the color of an individual cell. The color is determined when the cell is renderer, which is why you need to use a renderer.

it colors the table completely

Yes, once you set the background of the renderer all cells in the future will use that color. You need to reset the color to its default before rendering each cell

the background must be red just in case it's a number AND it's higher than 24,

Then do a positive check and forget about all those negative checks.

Using all the above suggestions you might have a renderer something like:

class ColorRenderer extends DefaultTableCellRenderer
{
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

if (isSelected)
setBackground( table.getSelectionBackground() );
else
{
setBackground( table.getBackground() );

try
{
int number = Integer.parseInt( value.toString() );

if (number > 24)
setBackground( Color.RED );
}
catch(Exception e) {}
}

return this;
}
}

Change only one cell's color in JTable

The row and column number are passed into getTableCellRendererComponent. So you could do something like:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setText(value.toString());
if (row==12 && column==2) {
setBackground(Color.RED);
}
return this;
}

How to change background color of an edited cell in JTable?

First, get the table's default selection background color:

Color color = UIManager.getColor("Table.selectionBackground");

Second, override prepareEditor(), as shown in this example, and set the background color of the editor component to match:

@Override
public Component prepareEditor(TableCellEditor editor, int row, int col) {
Component c = super.prepareEditor(editor, row, col);
c.setBackground(color);
return c;
}

Addendum: While technically correct, note that the editor component's color is typically managed by the corresponding UI delegate while active. An unfortunate choice may result in poor contrast and impaired usability. Thorough testing on target Look & Feels is warranted.

how to change background color of individual cell in JTable in java?

You can use XxxCellRenderer, better and easiest is to use prepareRenderer()

for correct code you have to override or test inside if-else follows patameters

  • isSelected

  • hasFocus

  • column

  • row

Please to check answers and one question about similair issue, there are two simple ways, sorry I‘m in FRI trafic, brrrrr



Related Topics



Leave a reply



Submit