Trying to color specific rows of JTable using Custom Renderer, instead all my rows are colored

空扰寡人 提交于 2019-12-13 02:36:41

问题


for my Java program basically when the value in column 4 of my JTable is greater than column 3, I want those specific rows to be colored in red and not the other rows.

I have implemented the following code, but for some reason all my rows are getting colored in red rather than just the ones matching the criteria.

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer(){
    @Override
    public Component getTableCellRendererComponent(JTable table, 
                   Object value, boolean isSelected, boolean hasFocus, int row, int col) {

        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);

        int Value1= Integer.parseInt(table.getModel().getValueAt(row, 3).toString());
        int Value2= Integer.parseInt(table.getModel().getValueAt(row, 4).toString());
        if (Value2>=Value1) {                        
            setBackground(Color.red);
        } 
        return this;
    }   
});

Any suggestions/tips on how to fix this?


回答1:


A DefaultTableCellRenderer instance uses a template component to render all cells (namely itself, see documentation). Once you set its color, the template will have that color and will be applied to all subsequent cells.

What you need to do is in your logic, set the color to red in the cases you need, and set it to the default background color in all other cases.

if(!isSelected) {
    if (Value2>=Value1) {                        
        setBackground(Color.red);
    } else {
        setBackground(table.getBackground()); // or use another color for another background
    }
}

Looking at your code again, I'm noticing you are making an error with regards to model versus view indices. The getTableCellRendererComponent method is called with view indices, yet you are using these to index the model (eg in table.getModel().getValueAt(row, 3)). When your table is sorted, results will be incorrect as model indices and view indices will differ.

If you need to get values from the model, you first need to convert the view indices to model indices. Use JTable.convertRowIndexToModel and JTable.convertColumnIndexToModel to do that. Eg:

int modelRowId = table.convertRowIndexToModel(row);
int Value1= Integer.parseInt(table.getModel().getValueAt(modelRowId, 3).toString());
int Value2= Integer.parseInt(table.getModel().getValueAt(modelRowId, 4).toString());



回答2:


Take a look at Table Row Rendering which shows how to do this by overriding the prepareRenderer(...) method of the JTable.

Using this approach you don't need a custom renderer for each data type in the table.



来源:https://stackoverflow.com/questions/35685885/trying-to-color-specific-rows-of-jtable-using-custom-renderer-instead-all-my-ro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!