Reputation:
I read a lot of articles and finally got my JTable rendering as per my requirements but the problem is when the table is scrolled by user, some of the other hidden parts of jtable are also colored as shown in image below
And when the user scrolls the table, other parts are also got colored like this
Why this happens? I read many articles and and all of them show exactly the same thing but this...
Here is my code
JTable table = new JTable()
{
public boolean isCellEditable(int rowIndex, int colIndex)
{
return false;
}
};
(DefaultTableCellRenderer)table.getTableHeader().getDefaultRenderer())
.setHorizontalAlignment(JLabel.CENTER);
table.setModel(new DefaultTableModel(new Object [][] {}, Columns));
table.setRowHeight(25);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getColumnModel().removeColumn(table.getColumnModel().getColumn(0));
table.setDefaultRenderer(Object.class, new 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(!table.getModel().getValueAt(row, 10).toString().equals("true"))
{
setBackground(new Color(246,137,137));
}
return this;
}
});
JScrollPane areaScrollPane = new JScrollPane(table);
areaScrollPane.setPreferredSize(new Dimension(width, height));
MyPanel.add(areaScrollPane);
All the articles show this way to render custom row on condition base. What's wrong in my code? Thanks for any support.
Upvotes: 1
Views: 1312
Reputation: 324118
if(!table.getModel().getValueAt(row, 10).toString().equals("true"))
{
setBackground(new Color(246,137,137));
}
The same renderer is used for all cells so once you set the background it will apply for all cells. So, I think you need something like:
if(!table.getModel().getValueAt(row, 10).toString().equals("true"))
{
setBackground(new Color(246,137,137));
}
else
setBackground( table.getBackground() );
You should also add code to make sure the cell is not selected so that the default selection color can be painted.
Instead of using a custom renderer you can also override the prepareRenderer(...)
method of JTable. Table Row Rendering show how you can render a row based on a value in that row.
Upvotes: 5