how to give a jtable cell different background colour - java

i am getting only last row coloured..
class CustomTableCellRenderer extends DefaultTableCellRenderer {
private Map<Integer, Color> mapColors;
public CustomTableCellRenderer() {
mapColors = new HashMap<>();
}
public void setRowColor(int row, Color color) {
// System.out.println(row + "...happy...." + color);
mapColors.put(row, color);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, 1);
Color color = mapColors.get(row);
if (color != null) {
cell.setBackground(color);
} else {
cell.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
}
row++;
return cell;
}
}

A cell renderer is a shared resource which is applied to ALL the cells for a given column. In order to provide customisation for a given row or rows, you need to provide a means by which you can remember which row you want and it's color, for example...
public class CustomTableCellRenderer extends DefaultTableCellRenderer {
private Map<Integer, Color> mapColors;
public CustomTableCellRenderer() {
mapColors = new HashMap<Integer, Color>();
}
public void setRowColor(int row, Color color) {
mapColors.put(row, color);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, 1);
Color color = mapColors.get(row);
if (color != null) {
cell.setBackground(color);
} else {
cell.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
}
return cell;
}
}
For example...
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DefaultTableModel model = new DefaultTableModel(new Object[]{"One"}, 6);
CustomTableCellRenderer renderer = new CustomTableCellRenderer();
renderer.setRowColor(0, Color.RED);
renderer.setRowColor(1, Color.GREEN);
renderer.setRowColor(2, Color.BLUE);
renderer.setRowColor(3, Color.PINK);
renderer.setRowColor(4, Color.MAGENTA);
JTable table = new JTable(model);
table.getColumnModel().getColumn(0).setCellRenderer(renderer);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
class CustomTableCellRenderer extends DefaultTableCellRenderer {
private Map<Integer, Color> mapColors;
public CustomTableCellRenderer() {
mapColors = new HashMap<Integer, Color>();
}
public void setRowColor(int row, Color color) {
mapColors.put(row, color);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, 1);
Color color = mapColors.get(row);
if (color != null) {
cell.setBackground(color);
} else {
cell.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
}
return cell;
}
}
}
See Concepts: Editors and Renderers for more details

Related

JTable change color for entire column when values changed - Swing

I tried to find here for a long time answer for my question but without the exact result i expected.
I have JTable which every time i am changing values in entire column (only in one column every time).
I want to listen to a table changes and when data changes in the column, the color in the column will be changed too and all other columns will be in the default color.
This is the code for the table listener:
Class CustomCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component rendererComp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
table.getModel().addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
if(***here i want to know which column changed or something like that***){
rendererComp.setBackground(Color.CYAN);
}
}
});
return rendererComp ;
}
}
and this is the code for the table creation:
private void createTable() {
tablePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
DefaultTableModel tableModel = new DefaultTableModel(){
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
contentTable = new JTable(tableModel);
contentTable.setGridColor(Color.LIGHT_GRAY);
for(int i=0; i<columnSize; i++) {
tableModel.addColumn("0");
}
for(int i=0; i<rawSize; i++) {
tableModel.addRow(new Object[] { "" });
}
for(int i=0; i<rawSize; i++) {
for(int j=0; j<tableModel.getRowCount(); j++) {
tableModel.setValueAt("0", j, i);
}
}
for(int i=0; i<ramSize; i++) {
contentTable.getColumnModel().getColumn(i).setCellRenderer(new CustomCellRenderer());
}
JScrollPane scrollPane = new JScrollPane(contentTable);
scrollPane.setPreferredSize(new Dimension(400, 150));
tablePanel.add(scrollPane);
}
Store the desired state in the TableModel; let the TableCellRenderer use the state to condition the view accordingly. In the example below, as soon as setValueAt() updates any cell, edited is marked true. The render, which is applied to column zero, changes the display accordingly. Note how clearEdited() invokes fireTableDataChanged() to force the table to render all cells when called in the Clear handler.
Addendum: The update below shows one approach to handling multiple columns independently. The CustomModel now contains a Map<Integer, Boolean> to store the edited state for each column to which the CustomRenderer is applied. As an aside, the CustomRenderer now invokes convertColumnIndexToModel() and sets the selection color correctly.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
/**
* #see http://stackoverflow.com/a/37439731/230513
*/
public class Test {
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CustomModel model = new CustomModel();
model.setColumnIdentifiers(new String[]{"A", "B"});
for (int i = 0; i < 16; i++) {
model.addRow(new String[]{"A:" + i, "B:" + i});
}
JTable table = new JTable(model) {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(100, getRowHeight() * getRowCount() / 2);
}
};
table.getColumnModel().getColumn(0).setCellRenderer(new CustomRenderer(model));
table.getColumnModel().getColumn(1).setCellRenderer(new CustomRenderer(model));
f.add(new JScrollPane(table));
JPanel p = new JPanel();
p.add(new JButton(new UpdateAction("Update A", model, 0)));
p.add(new JButton(new UpdateAction("Update B", model, 1)));
p.add(new JButton(new AbstractAction("Clear") {
#Override
public void actionPerformed(ActionEvent e) {
model.clearEdited(0);
model.clearEdited(1);
}
}));
f.add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class CustomModel extends DefaultTableModel {
private final Map<Integer, Boolean> edited = new HashMap<>();
public boolean isEdited(int column) {
return edited.get(column) != null && edited.get(column);
}
public void clearEdited(int column) {
edited.put(column, false);
fireTableDataChanged();
}
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
#Override
public void setValueAt(Object aValue, int row, int column) {
super.setValueAt(aValue, row, column);
edited.put(column, true);
}
}
private static class CustomRenderer extends DefaultTableCellRenderer {
private final CustomModel model;
public CustomRenderer(CustomModel model) {
this.model = model;
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int col) {
Component c = super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, col);
if (model.isEdited(table.convertColumnIndexToModel(col))) {
c.setBackground(Color.cyan);
} else if (isSelected) {
c.setBackground(table.getSelectionBackground());
} else {
c.setBackground(table.getBackground());
}
return c;
}
}
private static class UpdateAction extends AbstractAction {
private final CustomModel model;
private final int column;
public UpdateAction(String name, CustomModel model, int column) {
super(name);
this.model = model;
this.column = column;
}
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < model.getRowCount(); i++) {
model.setValueAt(model.getValueAt(i, column), i, column);
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}

Checkboxes in a JTabel column instead of boolean values using CellRenderer

I am adding a cell renderer to one of my column. Which is intended to return checkbox instead of boolean values. By doing below stuff I can able to get the checkboxes on passing boolean values but I am unable to check/uncheck the boxes.
It works fine if I override the getColumnClass() of DataTableModel.
But I need it with renderers
public class CustomRenderer
{
Table table = new JTable();
public DefaultTableModel getDtmInsurance()
{
if (dtmInsurance == null)
{
String[] columns = { "LIC ID", "Delete" };
dtmInsurance = new DefaultTableModel(columns, 0)
{
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column)
{
if (column == 1)
return true;
return false;
}
};
dtmInsurance.setColumnIdentifiers(columns);
table.setModel(dtmInsurance);
Object[] addInsurance = { "0", false };
dtmInsurance.addRow(addInsurance);
}
table.getColumnModel().getColumn(1).setCellRenderer(new MyRenderer());
return dtmInsurance;
}
class MyRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
JCheckBox check = new JCheckBox();
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column)
{
Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
if (obj instanceof Boolean)
{
return check;
}
return cell;
}
}
}
Now, you could go through the exercise of implementating your own renderer and editor OR you could let the table API do it for you.
You could just add
#Override
public Class<?> getColumnClass(int columnIndex) {
Class type = String.class;
switch (columnIndex) {
case 0:
type = Integer.class;
break;
case 1:
type = Boolean.class;
break;
}
return type;
}
To your dtmInsurance implementation and get
for free.
Otherwise you should have a look at Concepts: Editors and Renderers and Using Other Editors for more details about making it yourself :P
A custom editor might look something like...
public class MyBooleanEditor extends AbstractCellEditor implements TableCellEditor {
private JCheckBox check = new JCheckBox();
#Override
public Object getCellEditorValue() {
return check.isSelected();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof Boolean) {
check.setSelected((Boolean)value);
}
return check;
}
}
Which you would be able to use similarly to...
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.AbstractCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
public class CustomRenderer extends JPanel {
private JTable table = new JTable();
private DefaultTableModel dtmInsurance;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CustomRenderer());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public CustomRenderer() {
setLayout(new BorderLayout());
table.setModel(getDtmInsurance());
TableColumn column = table.getColumnModel().getColumn(1);
column.setCellEditor(new MyBooleanEditor());
column.setCellRenderer(new MyBooleanRenderer());
add(new JScrollPane(table));
}
public DefaultTableModel getDtmInsurance() {
if (dtmInsurance == null) {
String[] columns = {"LIC ID", "Delete"};
dtmInsurance = new DefaultTableModel(columns, 0) {
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
if (column == 1) {
return true;
}
return false;
}
};
dtmInsurance.setColumnIdentifiers(columns);
table.setModel(dtmInsurance);
Object[] addInsurance = {"0", false};
dtmInsurance.addRow(addInsurance);
}
return dtmInsurance;
}
class MyBooleanRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
JCheckBox check = new JCheckBox();
#Override
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
if (obj instanceof Boolean) {
return check;
}
return cell;
}
}
public class MyBooleanEditor extends AbstractCellEditor implements TableCellEditor {
private JCheckBox check = new JCheckBox();
#Override
public Object getCellEditorValue() {
return check.isSelected();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof Boolean) {
check.setSelected((Boolean)value);
}
return check;
}
}
}
But if I have 10 rows in my table, the checkbox which i selected first as soon as starting the program, only for that checkbox I can able to check/uncheck. Not for all
You cell renderer doesn't update the state of the checkbox each time it's called, it's just return a empty checkbox.
Something more like...
class MyBooleanRenderer implements TableCellRenderer {
private static final long serialVersionUID = 1L;
JCheckBox check = new JCheckBox();
#Override
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
check.setSelected(false);
if (obj instanceof Boolean) {
check.setSelected((Boolean)obj);
}
if (isSelected) {
check.setForeground(table.getSelectionForeground());
check.setBackground(table.getSelectionBackground());
} else {
check.setForeground(table.getForeground());
check.setBackground(table.getBackground());
}
return check;
}
}
Seems to work

JTable cell renderer skips Boolean column

Below is a picture of my JTable. My problem is that the blue background every other row isn't present in the 4th column. My table model and cell renderer are also below.
Table model:
public class MyTableModel extends DefaultTableModel {
public int getColumnCount() {
return columnNames.length;
}
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return data.length;
}
public Object getValueAt(int row, int column) {
return data[row][column];
}
public Class getColumnClass(int column) {
return (getValueAt(0, column).getClass());
}
public void setValueAt(Object value, int row, int column) {
data[row][column] = value;
}
public boolean isCellEditable(int row, int column) {
return (column == 3);
}
}
Cell Renderer:
private class CalendarRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean focused, int row, int column) {
super.getTableCellRendererComponent(table, value, selected, focused, row, column);
setBackground(new Color(0xFFFFFF));
if (row % 2 == 1) {
setBackground(new Color(0xE8F2FE)); //light blue
}
setBorder(null);
setForeground(Color.black);
return this;
}
}
The "default" cell renderer for Boolean is a check box. If you want to change the way that this cell gets rendered, you're going to have to supply your own TableCellRenderer that implements your own logic.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class TestTableCellRenderer {
public static void main(String[] args) {
new TestTableCellRenderer();
}
public TestTableCellRenderer() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTable table = new JTable();
table.setModel(new TableModel());
table.setDefaultRenderer(Boolean.class, new BooleanCellRenderer());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TableModel extends AbstractTableModel {
private List<Boolean> values = new ArrayList<>(25);
public TableModel() {
for (int index = 0; index < 25; index++) {
values.add((((int) Math.round(Math.random() * 1)) == 0 ? false : true));
}
}
#Override
public int getRowCount() {
return values.size();
}
#Override
public int getColumnCount() {
return 1;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return values.get(rowIndex);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return Boolean.class;
}
}
public static class BooleanCellRenderer extends JCheckBox implements TableCellRenderer {
private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
public BooleanCellRenderer() {
setLayout(new GridBagLayout());
setMargin(new Insets(0, 0, 0, 0));
setHorizontalAlignment(JLabel.CENTER);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Boolean) {
setSelected((Boolean) value);
}
if (!isSelected) {
setBackground(new Color(0xFFFFFF));
if (row % 2 == 1) {
setBackground(new Color(0xE8F2FE)); //light blue
}
setForeground(Color.black);
} else {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
}
if (hasFocus) {
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
} else {
setBorder(noFocusBorder);
}
return this;
}
}
}
See Table Row Rendering for a solution that doesn't require you to keep creating custom renderers every time you have columns with different data.
JTable table = new JTable( model )
{
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
// Alternate row color
if (!isRowSelected(row))
c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY);
return c;
}
};

Change background color of one cell in JTable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Changing Swing JTable Cell Colors
I have developed a swing application which shows a JTable. I want that when the user modify a cell value, the cell modified change color.
This is the code that I run when the user modify a cell:
this.myTable.getColumnModel().getColumn(column).setCellRenderer(new StatusColumnCellRenderer());
And this is the code of my cell Render class:
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.
TableModelLotti tableModel = (TableModelLotti) table.getModel();
if(isSelected)
l.setBackground(Color.GREEN);
//Return the JLabel which renders the cell.
return l;
}
}
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.
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();
}
});
}
}

How to change the color of particular cell in JXTreeTable dynamically

I am using JXTreeTable for making treetable structure now I want to change the color of specific cell dynamically. How can I change the color of cell?
I found this code to change the color, but this is not working.
Here is Code:
leftTree.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
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);
if(Integer.parseInt(rowvalue[0])==row && column==0) {
c.setBackground(Color.red);
}
return c;
}
});
Use highlighters.
addHighlighter(new ColorHighlighter());
If the cell contains text with the name of the color then it would be possible to modify the value.
import java.awt.Color;
import java.awt.Component;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
public class MainClass extends JFrame {
ColorName colors[] = { new ColorName("Red"), new ColorName("Green"), new ColorName("Blue"),
new ColorName("Black"), new ColorName("White") };
public MainClass() {
super("Table With DefaultCellEditor Example");
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JTable table = new JTable(new AbstractTableModel() {
ColorName data[] = { colors[0], colors[1], colors[2], colors[3], colors[4], colors[0],
colors[1], colors[2], colors[3], colors[4] };
public int getColumnCount() {
return 3;
}
public int getRowCount() {
return 10;
}
public Object getValueAt(int r, int c) {
switch (c) {
case 0:
return (r + 1) + ".";
case 1:
return "Some pithy quote #" + r;
case 2:
return data[r];
}
return "Bad Column";
}
public Class getColumnClass(int c) {
if (c == 2)
return ColorName.class;
return String.class;
}
public boolean isCellEditable(int r, int c) {
return c == 2;
}
public void setValueAt(Object value, int r, int c) {
data[r] = (ColorName) value;
}
});
table.setDefaultEditor(ColorName.class, new DefaultCellEditor(new JComboBox(colors)));
table.setDefaultRenderer(ColorName.class, new TableCellRenderer());
table.setRowHeight(20);
getContentPane().add(new JScrollPane(table));
}
public static void main(String args[]) {
MainClass ex = new MainClass();
ex.setVisible(true);
}
public class ColorName {
String cname;
public ColorName(String name) {
cname = name;
}
public String toString() {
return cname;
}
}
public class TableCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int col)
{
// get the DefaultCellRenderer to give you the basic component
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
// apply your rules
if (value.toString().equals("Red"))
c.setBackground(Color.RED);
else
c.setBackground(Color.GRAY);
return c;
}
}
}

Categories