问题描述:

I have a java program that adds rows into a jtable. When I add a row, it does price check for that row and if it is greater than 100, it highlights green immediately after it has been added. This is currently my code, and all it does is highlight everything green. What's my problem?

class YourTableCellRenderer

extends 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 (row == table.getRowCount()-1) {

c.setBackground(Color.GREEN);

}

return c;

}

}

model.addRow(new Object[] {"col1", "col2"});

if(price>100)

{

table.setDefaultRenderer(Object.class, new YourTableCellRenderer());

}

网友答案:

You need to set the check in the YourTableCellRenderer itself. The render is called after the data model returns a value. All this takes place when the component is being painted, so I don't know where in the process this code is:

if(price>100)
{
    table.setDefaultRenderer(Object.class, new YourTableCellRenderer());
}

But once the renderer is set for the table that's it - the redering doesn't happen when the data model is updated (I assume that's what the code does). It happens when the screen gets painted in response to an event (like focus gained or repaint() programmatically called).

相关阅读:
Top