Skip to main content

why Renderer does not work (JTable)?

3 replies [Last post]
nopox
Offline
Joined: 2006-02-17

why my Renderer (for JTable) does not work?

<br />
class ColoredRenderer extends DefaultTableCellRenderer {<br />
public Component getTableCellRendererComponent(JTable table, Object value,<br />
                      boolean selected, boolean focused, int row, int column) {<br />
if ((row % 2) == 0) {<br />
 setBackground(Color.red);<br />
}<br />
else {<br />
  setBackground(null);<br />
}<br />
super.getTableCellRendererComponent(table, value, selected, focused, row, column);<br />
return this;<br />
}<br />

in the main function:

<br />
/* skippped */<br />
DefaultTableModel alarmModel = new DefaultTableModel(<br />
new String {"#1", "#2"}<br />
);<br />
JTable alarmTable = new JTable(alarmModel);<br />
ColoredRenderer coloredRenderer = new ColoredRenderer();<br />
alarmTable.setDefaultRenderer(new String("").getClass(), coloredRenderer);<br />
/* skipped */<br />

Message was edited by: nopox

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
shan-man
Offline
Joined: 2006-02-17

Hi nopox,

> why my Renderer (for JTable) does not work?

When you say your renderer doesn't work, I assume you mean that it doesn't draw cells in the color you want. If that's the case, then it's because of where you've placed the call to "super.getTableCell...". The superclass behavior also sets the colors of the renderer, thereby overriding what you've just set. To fix your code, move the call to "super.getTableCell..." to be the first line in your method.

[code]
> class ColoredRenderer extends DefaultTableCellRenderer {
> public Component getTableCellRendererComponent(JTable table, Object value,
> boolean selected, boolean focused, int row, int column) {

===> Move it here

> if ((row % 2) == 0) {
> setBackground(Color.red);
> }
> else {
> setBackground(null);
> }
> super.getTableCellRendererComponent(table, value, selected, focused, row, column);

Move the previous line ^^^^^^

> return this;
> }
[/code]
Good luck!
Shannon

vdkuil
Offline
Joined: 2006-02-17

See
http://uic.sourceforge.net/api/uic/widgets/TwoColorCellRenderer.html
for a working cellrenderer that uses TwoColors (For example by setting the UICTheme).

mgrev
Offline
Joined: 2003-08-12

Hello, please surround you code with
[ code ]
System.out.println bla bla
[ /code ]

(without the spaces)

It will be much easier to read.

(You can edit your message)

Regards,
Mikael