here is my problem
I read a DB and show the data via the renderer. Shown data must be centered and bgcolor must change according to the value of the cell.
Following is the renderer. First table.getColumnModel() shows the centered value, second one calls a customer renderer to change the color. If I remove the comment on the second call I get the bgcolor but not the centered value and viceversa
for (int row = 0; row < table.getColumnCount(); row++) {
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
table.getColumnModel().getColumn(row).setCellRenderer(centerRenderer);
//table.getColumnModel().getColumn(row).setCellRenderer(new CustomRenderer());
}
This is the Custom renderer
class CustomRenderer extends DefaultTableCellRenderer
{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(table.getValueAt(row, column).equals("A")){
cellComponent.setBackground(Color.YELLOW);
} else if(table.getValueAt(row, column).equals("B")){
cellComponent.setBackground(Color.GRAY);
}
else {cellComponent.setBackground(Color.white);}
return cellComponent;
}
}
How can I obtain a colored and center cell?
Than you
paps
Here a short snippet demonstrating what I think you are trying to achieve:
public class Testing {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Testing();
}
});
}
public Testing() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
String[] colNames = { "Col1", "Col2" };
Object[][] data = { { "A", "B" }, { "B", "C" } };
JTable table = new JTable(data, colNames);
CustomRenderer renderer = new CustomRenderer();
renderer.setHorizontalAlignment(JLabel.CENTER);
// table.setDefaultRenderer(String.class, renderer); // if you want to only
// color and center all strings
for (int col = 0; col < table.getColumnCount(); col++) {
// if you want to color and center every entry of the table
table.getColumnModel().getColumn(col).setCellRenderer(renderer);
}
panel.add(table);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
class CustomRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
cellComponent.setBackground(Color.white); // white if not "A" or "B"
if (value instanceof String) {
String temp = (String) value;
if (temp.equals("A")) {
cellComponent.setBackground(Color.YELLOW);
} else if (temp.equals("B")) {
cellComponent.setBackground(Color.GRAY);
}
}
return cellComponent;
}
}
}
The result will look like:
Note that your custom renderer only has to be created once, not on every loop. The issue in your code was, that you didn't use your own renderer, but a DefaultTableCellRenderer instead. Also, if you want to only use the custom rendering on a specific class type, e.g. only on String objects, you can use the commented out line instead of iterating through all columns of the table.
And of course you can add further restrictions to the CustomRenderer according to your needs.
Related
I am trying to change the color of some cells in my JTable. I have tried to override getTableCellRendererComponent in a simple example, and it works nice. But when I do the same in my project nothing changes...
I have my JPanel with my JTable in a Box like this:
boxTable=Box.createHorizontalBox();
box2Table.add(boxTable);
//JTable
tablaContador = new JTable(datosContador,cabeceraContador);
//MODIF COLOR
tablaContador.setDefaultRenderer(Object.class, new ColorRenderer());
Doing:
System.out.println(tablaContador.getColumnClass(3));
I can know that the first parameter of setDefaultRenderer is Object.class
I don't know if the problem is here... i have only strings in the Table, but I have tried String.class and nothing happens
Then I modify some things of JTable's Cells:
tablaContador.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
boxTable.add(tablaContador);
//Align cells
for (int i=0; i<cabeceraContador.length;i++){
tablaContador.getColumnModel().getColumn(i).setCellRenderer(alinearCeldas);
}
//Modify cells' width
tablaContador.getColumnModel().getColumn(0).setMinWidth(150);
for (int i=1; i<cabeceraContador.length;i++){
tablaContador.getColumnModel().getColumn(i).setMaxWidth(40);
}
//Scroll for the Table
scrollContador=new JScrollPane(tablaContador,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollContador.setPreferredSize(new Dimension(1000,80));
scrollContador.setMinimumSize(new Dimension(1000,80));
scrollContador.setMaximumSize(new Dimension(2000,80));
//Add scroll to the box
box2Table.add(scrollContador);
And my ColorRenderer class is:
public class ColorRenderer extends DefaultTableCellRenderer{
private Component c;
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,int row, int column) {
c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(Color.BLUE);
return c;
}
}
Table result
So It does not work in my project i don't know why
any idea?
thaks!
I see:
tablaContador.setDefaultRenderer(Object.class, new ColorRenderer());
and then I see:
for (int i=0; i<cabeceraContador.length;i++)
{
tablaContador.getColumnModel().getColumn(i).setCellRenderer(alinearCeldas);
}
The assignment of the renderer to a specific column takes precedence over setting the default renderer so your color renderer is never used.
Not exactly what you are trying to do, but I would guess you need to add the color rendering logic to the alignment renderer. In other words all the rendering logic must be contained in a single renderer. You can't merge multiple renderers.
Here is a simple example of a custom renderer:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableRenderer extends JPanel
{
public TableRenderer()
{
String[] columnNames = {"String", "Integer"};
Object[][] data =
{
{"A", new Integer(1)},
{"B", new Integer(2)},
{"C", new Integer(10)},
{"D", new Integer(4)}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model );
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
// Override default renderer on a specific column
TableCellRenderer colorRenderer = new ColorRenderer();
table.getColumnModel().getColumn(1).setCellRenderer( colorRenderer );
}
/*
** Color the focused cell
*/
class ColorRenderer extends DefaultTableCellRenderer
{
public ColorRenderer()
{
super();
setHorizontalAlignment(JLabel.RIGHT);
}
#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( null );
try
{
int number = Integer.parseInt( value.toString() );
if (number > 9)
setBackground( Color.RED );
}
catch(Exception e) {}
}
return this;
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Color Renderer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TableRenderer());
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
I am sorry if the title is not explanatory enough.
I have written a small extension to DefaultTableRenderer class in Java in order to specify cellBackgourd, cellForeground, Alignment and decimal control. I using this class in matlab to control and customise JIDE tables. But have re-created the issue in Java, in order to increase chances of a reply or a possible workaround.
I am successfully able to set cell Background, Foreground, alignment and decimal places as required when the table initialises and displays. However, as soon as I select a row/cell I loose decimal control on displayed data as shown in figure below. Please note that I am using specific cell selection colours, I guess, I am not implementing it properly.
I think, the problem is one of last two lines:
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
or
return cell;
Java code:
import java.awt.*;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.table.*;
public class DecimalPlacesInTable extends JFrame {
public static void main( String[] args ) {
DecimalPlacesInTable frame = new DecimalPlacesInTable();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
public DecimalPlacesInTable() {
Object[] columnNames = { "A", "B", "C" };
Object[][] data = {
{new Double( 850.503 ), new Double( 850.545 ), new Double( 80.54553 ) },
{new Double( 50.52503 ), new Double( 36.4554 ), new Double( 50.41453 ) },
{new Double( 80.544653 ), new Double( 8.3 ), new Double( 80.4553 ) },
{new Double( 50.1553 ), new Double( 246.0943 ), new Double( 50.455 ) }};
JTable table = new JTable(data, columnNames);
// Tell the table what to use to render our column of doubles
for (int i=0; i<3; i++) {
table.getColumnModel().getColumn(i).setCellRenderer(new DecimalFormatRenderer());
getContentPane().add(new JScrollPane(table));
}
}
// Custom Renderer class
static class DecimalFormatRenderer extends DefaultTableCellRenderer
{
public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JComponent cell = (JComponent) super.getTableCellRendererComponent
(table, value, isSelected, hasFocus, row, column);
// set color
cell.setBackground(new Color(0xC8C8C8));
cell.setForeground(new Color(0xFFFFFF));
//set Alignment
((JLabel) cell).setHorizontalAlignment(SwingConstants.CENTER);
//set selection colors
if (isSelected) {
cell.setBackground(new Color(0x3399FF));
cell.setForeground(new Color(0x000000)); // AM
} else {
// set decimals
DecimalFormat DecimalFormatter = new DecimalFormat("#.00");
value = DecimalFormatter.format(value);
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
return cell;
}
}
}
From Concepts: Editors and Renderers - How to Use Tables (The Java? Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
It is easy to customize the text or image rendered by the default renderer, DefaultTableCellRenderer. You just create a subclass and implement the setValue method so that it invokes setText or setIcon with the appropriate string or image. For example, here is how the default date renderer is implemented:
import java.awt.*;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.table.*;
public class DecimalPlacesInTable2 extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
DecimalPlacesInTable2 frame = new DecimalPlacesInTable2();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
});
}
public DecimalPlacesInTable2() {
Object[] columnNames = { "A", "B", "C" };
Object[][] data = {
{850.503, 850.545, 80.54553},
{50.52503, 36.4554, 50.41453},
{80.544653, 8.3, 80.4553},
{50.1553, 246.0943, 50.455}
};
//JTable table = new JTable(data, columnNames);
TableModel model = new DefaultTableModel(data, columnNames) {
#Override public Class<?> getColumnClass(int column) {
return Double.class;
}
};
JTable table = new JTable(model);
// Tell the table what to use to render our column of doubles
for (int i = 0; i < 3; i++) {
table.getColumnModel().getColumn(i).setCellRenderer(new DecimalFormatRenderer());
//getContentPane().add(new JScrollPane(table));
}
getContentPane().add(new JScrollPane(table));
}
// Custom Renderer class
static class DecimalFormatRenderer extends DefaultTableCellRenderer {
private final DecimalFormat formatter = new DecimalFormat("#.00");
#Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JLabel cell = (JLabel) super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
//set Alignment
cell.setHorizontalAlignment(SwingConstants.CENTER);
//set selection colors
if (isSelected) {
cell.setBackground(new Color(0x3399FF));
cell.setForeground(new Color(0x000000)); // AM
} else {
// set color
cell.setBackground(new Color(0xC8C8C8));
cell.setForeground(new Color(0xFFFFFF));
}
// // set decimals
// if (value instanceof Double) {
// cell.setText(formatter.format(value));
// }
return cell;
}
#Override public void setValue(Object value) {
setText(value instanceof Double ? formatter.format(value) : "");
}
}
}
I am trying to create a TableCellRenderer which changes the background of row. I am overriding the prepareRenderer, it changes the background of row on selection but as soon as I change the selection the default background color(white) is set to previous selected row and newer row gets the background color(light grey).
Here is my code:
final JTable table = new JTable(model)
{
#Override
public Component prepareRenderer(TableCellRenderer renderer,int row,int column)
{
Component comp=super.prepareRenderer(renderer,row, column);
int modelRow=convertRowIndexToModel(row);
if(!isRowSelected(modelRow))
comp.setBackground(Color.WHITE);
else
comp.setBackground(Color.LIGHT_GRAY);
return comp;
}
};
My output screen:
I want to do like this:
For your requirement you can do the following:
IN your model keep a hidden column of flag values. Assume that your hidden column is 5 column and you can code as below:
final JTable table = new JTable(model)
{
#Override
public Component prepareRenderer(TableCellRenderer renderer,int row,int column)
{
Component comp=super.prepareRenderer(renderer,row, column);
int modelRow=convertRowIndexToModel(row);
if((Boolean)getValueAt(row,5))
comp.setBackground(Color.LIGHT_GRAY);
else
comp.setBackground(Color.WHITE);
return comp;
}
};
Your flag values contain the Boolean object.
Try this:
table.setDefaultRenderer(Object.class, new TableCellRenderer(){
private DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
//table.setBackground(Color.YELLOW);
//table.setSelectionBackground(Color.YELLOW);
if(isSelected){
c.setBackground(Color.YELLOW);
}else{
if (row%2 == 0){
c.setBackground(Color.WHITE);
}
else {
c.setBackground(Color.LIGHT_GRAY);
} }
return c;
}
});
I've been looking around for a solution to this and I can't make head nor tail from various places of how to get my table to do coloured rows without asking my own question.
From every place I've looked I gather I need to use a cell renderer but the problem is I don't know how to apply it to my own situation.
So I have a simple JTable with 3 columns and I simply want each row to be highlighted in either green, yellow or red depending on the value of a separate variable (not displayed in the table).
It seems like it should be really simple but I can't get how to do it. If it helps my table is defined like:
studentTableModel = new DefaultTableModel(new Object[]{"Name", "StudentNo", "Part"}, 0);
jt_studentTable = new JTable(studentTableModel);
jt_studentTable.getColumnModel().getColumn(2).setPreferredWidth(10);
studentTableModel.addRow(new Object[]{"(empty)", "(empty)", "(empty)"});
JScrollPane jsp_tableScroller = new JScrollPane(jt_studentTable);
jsp_tableScroller.setPreferredSize(new Dimension(200,190));
middleCentrePanel.add(jsp_tableScroller);
The rows in the table change depending of the selection of a combo box.
Thanks in advance.
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class RowRendering {
private static Object[] columnName = {"Yes", "No"};
private static Object[][] data = {
{"Y", "N"},
{"N", "Y"},
{"Y", "N"}
};
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
JTable table = new JTable(data, columnName);
table.getColumnModel().getColumn(0).setCellRenderer(new CustomRenderer());
table.getColumnModel().getColumn(1).setCellRenderer(new CustomRenderer());
frame.add(new JScrollPane(table));
frame.setTitle("Rendering in JTable");
frame.pack();
frame.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}
class CustomRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 6703872492730589499L;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(row == 0){
cellComponent.setBackground(Color.YELLOW);
} else if ( row == 1){
cellComponent.setBackground(Color.GRAY);
} else {
cellComponent.setBackground(Color.CYAN);
}
return cellComponent;
}
}
I simply want each row to be highlighted in either green, yellow or red depending on the value of a separate variable (not displayed in the table).
Renderers work on data in the table. That is components can only paint themselves when they have all the information needed to do the job.
So somehow you need to add the information to the table. This might be done be adding a 4th column that is hidden. Then the table still has access to the information required.
Then maybe you can use the suggestion in Table Row Renderering.
Maybe this works for you:
class MyCellRenderer extends DefaultTableCellRenderer {
String separatedVariable;
public MyCellRenderer(String separatedVariable) {
this.separatedVariable = separatedVariable;
}
#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);
c.setBackground(Color.WHITE);
c.setForeground(Color.BLACK);
JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
if (separatedVariable.equals("YOUR VALUE TO GREEN")) {
l.setBackground(Color.GREEN);
return l;
} else {
if (separatedValue.equals("YOUR VALUE TO YELLOW")) {
l.setBackground(Color.YELLOW);
return l;
} else if (separatedValue.equals("YOUR VALUE TO RED")) {
l.setBaground(Color.RED);
return l;
}
}
return c;
}
}
I just had this same question, but a bit more complicated, since I already had several different renderers for each column, depending on the datatype.
But I found that this works like a charm:
public class MyTable extends JTable {
#Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component result = super.prepareRenderer(renderer, row, column);
if (mustBeYellow(row, column)) {
result.setBackground(Color.yellow);
}
return result;
}
private boolean mustBeYellow(int row, int column) {
// implement this depending on your data..
return false;
}
}
Even I read and test answers by #kleopatra
How do I correctly use customer renderers to paint specific cells in a JTable?
particular one table header color java swing
about super.getTableCellRendererComponent(...) must be last code line before returns, I'm not able to write correct Renderer by those suggestion, for me works only this way
JLabel is added for Borders, HorizontalAlignment and Foreground, especially Background caused me a few non_senses by using Component instead of JLabel, (not important here somehow)
from SSCCE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class SelectedTableHeader {
private JFrame frame = new JFrame("Table Demo");
private JTableHeader header;
private Object selectedColumn = null;
private String[] columnNames = {"String", "Integer", "Float", "Double", "Locale & Double", "Boolean"};
private Object[][] data = {
{"aaa", new Integer(12), new Float(12.15), new Double(100.05), new Double(12.05), true},
{"bbb", new Integer(5), new Float(7.154), new Double(6.1555), new Double(417.55), false},
{"CCC", new Integer(92), new Float(0.1135), new Double(3.1455), new Double(11.05), true},
{"ddd", new Integer(12), new Float(31.15), new Double(10.05), new Double(23.05), true},
{"eee", new Integer(5), new Float(5.154), new Double(16.1555), new Double(17.55), false},
{"fff", new Integer(92), new Float(4.1135), new Double(31.1455), new Double(3.05), true}};
private TableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
private JTable table = new JTable(model);
public SelectedTableHeader() {
header = table.getTableHeader();
header.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JTableHeader h = (JTableHeader) e.getSource();
int i = h.columnAtPoint(e.getPoint());
Object o = h.getColumnModel().getColumn(i).getHeaderValue();
if (i < 0) {
selectedColumn = null;
return;
}
selectedColumn = o;
h.requestFocusInWindow();
}
});
final TableCellRenderer hr = table.getTableHeader().getDefaultRenderer();
header.setDefaultRenderer(new TableCellRenderer() {
private JLabel lbl;
#Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (selectedColumn == value) {
lbl = (JLabel) hr.getTableCellRendererComponent(table, value, true, true, row, column);
lbl.setBorder(BorderFactory.createCompoundBorder(lbl.getBorder(), BorderFactory.createLineBorder(Color.red, 1)));
lbl.setHorizontalAlignment(SwingConstants.LEFT);
} else {
lbl = (JLabel) hr.getTableCellRendererComponent(table, value, false, false, row, column);
lbl.setBorder(BorderFactory.createCompoundBorder(lbl.getBorder(), BorderFactory.createEmptyBorder(0, 5, 0, 0)));
lbl.setHorizontalAlignment(SwingConstants.CENTER);
}
if (column == 0) {
lbl.setForeground(Color.red);
} else {
lbl.setForeground(header.getForeground());
}
/*return (value == selectedColumn) ? hr.getTableCellRendererComponent(
table, value, true, true, row, column) : hr.getTableCellRendererComponent(
table, value, false, false, row, column);*/
return lbl;
}
});
table.setRowHeight(20);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scroll = new JScrollPane(table);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scroll);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
SelectedTableHeader selectedTableHeader = new SelectedTableHeader();
}
});
}
}
In my experience, it's better to get the DefaultTableCellHeaderRenderer when you overwrite any JTable Renderer. So, instead of messing with the JLabel from the Renderer directly, you grab the Renderer with super(). So, your code should look like this:
header.setDefaultRenderer(new DefaultTableCellHeaderRenderer() {
#Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
DefaultTableCellHeaderRenderer rendererComponent = (DefaultTableCellHeaderRenderer)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (selectedColumn == value) {
rendererComponent.setBorder(BorderFactory.createCompoundBorder(rendererComponent.getBorder(), BorderFactory.createLineBorder(Color.red, 1)));
rendererComponent.setHorizontalAlignment(SwingConstants.LEFT);
} else {
rendererComponent.setBorder(BorderFactory.createCompoundBorder(rendererComponent.getBorder(), BorderFactory.createEmptyBorder(0, 5, 0, 0)));
rendererComponent.setHorizontalAlignment(SwingConstants.CENTER);
}
if (column == 0) {
rendererComponent.setForeground(Color.red);
} else {
rendererComponent.setForeground(header.getForeground());
}
return rendererComponent;
}
});
To try and answer your questions directly:
Question 1:
Q: How do I correctly use customer renderers to paint specific cells in a JTable?
A: Your current code is setting a Renderer on the JTableHeader. To add a Renderer on your table cells would be similar code to what's above, only you'd set it through the Column model:
table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
// Set your code to render your component.
return renderer;
}
});
Note about this: JTables are column-based, which means that all the data in a certain column must be the same type (your SSCCE follows this convention). My favorite thing to do is to provide a custom Renderer for each type. For example, whenever I have a Date column, I use this renderer:
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import org.joda.time.LocalDate;
/**
*
* #author Ryan
*/
public class DateCellRenderer extends DefaultTableCellRenderer {
String pattern;
public DateCellRenderer(String pattern){
this.pattern = pattern;
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (value != null && value instanceof LocalDate) {
renderer.setText(((LocalDate)value).toString(pattern));
} else
throw new IllegalArgumentException("Only supported Object type is LocalDate.");
return renderer;
}
}
And I call this code with something similar:
table.getColumn("Date Entered").setCellRenderer(new DateCellRenderer("MMM dd, yyyy"));
Question 2:
Q: particular one table header color java swing
A: Umm.. Your SSCCE seems to have it figured out.
Question 3:
Q: about super.getTableCellRendererComponent(...) must be last code line before returns, I'm not able to write correct Renderer by those suggestion, for me works only this way
A: I'm not sure what you mean "must be last code line before returns." That is not the case, proven by the code snip I gave above
Question 4:
Q: JLabel is added for Borders, HorizontalAlignment and Foreground, especially Background caused me a few non_senses by using Component instead of JLabel, (not important here somehow)
A: Ok... the DefaultTableCellHeaderRenderer is sufficient for all of those, borders, alignment, foreground and background.
I had this happen to me in the past and I was convinced it had to do with the Cell Renderer, but the ArraysXxxException kind of Exceptions hunted me because I had forgotten to unselect and stop editing the cell before adding/removing rows. You should try clearSelection() and table.getCellEditor().stopCellEditing(); on your JTable before remove/add and see if that solves your problem.
First, of course, make sure it is editing:
if (table.isEditing()) {
table.getCellEditor().stopCellEditing();
}